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/status.py
|
netdev
|
python
|
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific implementation of netdev
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
if line.find(':') < 0:
continue
comps = line.split()
# Fix lines like eth0:9999..'
comps[0] = line.split(':')[0].strip()
# Support lines both like eth0:999 and eth0: 9999
comps.insert(1, line.split(':')[1].strip().split()[0])
ret[comps[0]] = {'iface': comps[0],
'rx_bytes': _number(comps[2]),
'rx_compressed': _number(comps[8]),
'rx_drop': _number(comps[5]),
'rx_errs': _number(comps[4]),
'rx_fifo': _number(comps[6]),
'rx_frame': _number(comps[7]),
'rx_multicast': _number(comps[9]),
'rx_packets': _number(comps[3]),
'tx_bytes': _number(comps[10]),
'tx_carrier': _number(comps[16]),
'tx_colls': _number(comps[15]),
'tx_compressed': _number(comps[17]),
'tx_drop': _number(comps[13]),
'tx_errs': _number(comps[12]),
'tx_fifo': _number(comps[14]),
'tx_packets': _number(comps[11])}
return ret
def freebsd_netdev():
'''
freebsd specific implementation of netdev
'''
_dict_tree = lambda: collections.defaultdict(_dict_tree)
ret = _dict_tree()
netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()
netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]
header = netstat[0].split()
for line in netstat[1:]:
comps = line.split()
for i in range(4, 13): # The columns we want
ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])
return ret
def sunos_netdev():
'''
sunos specific implementation of netdev
'''
ret = {}
##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:
# fetch device info
netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()
# prepare data
netstat_ipv4[0] = netstat_ipv4[0].split()
netstat_ipv4[1] = netstat_ipv4[1].split()
netstat_ipv6[0] = netstat_ipv6[0].split()
netstat_ipv6[1] = netstat_ipv6[1].split()
# add data
ret[dev] = {}
for i in range(len(netstat_ipv4[0])-1):
if netstat_ipv4[0][i] == 'Name':
continue
if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]
else:
ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])
for i in range(len(netstat_ipv6[0])-1):
if netstat_ipv6[0][i] == 'Name':
continue
if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]
else:
ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])
return ret
def aix_netdev():
'''
AIX specific implementation of netdev
'''
ret = {}
fields = []
procn = None
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():
# fetch device info
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0
#en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0
netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()
# add data
ret[dev] = []
for line in netstat_ipv4:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv4'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv4'][fields[i]] = comps[i]
for line in netstat_ipv6:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv6'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv6'][fields[i]] = comps[i]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netdev,
'FreeBSD': freebsd_netdev,
'SunOS': sunos_netdev,
'AIX': aix_netdev,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
|
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1254-L1431
| null |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import logging
import fnmatch
import collections
import copy
import time
import logging
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.config
import salt.minion
import salt.utils.event
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__file__)
__virtualname__ = 'status'
__opts__ = {}
# Don't shadow built-in's.
__func_alias__ = {
'time_': 'time'
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Not all functions supported by Windows
'''
if salt.utils.platform.is_windows():
return False, 'Windows platform is not supported by this module'
return __virtualname__
def _number(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
if text.isdigit():
return int(text)
try:
return float(text)
except ValueError:
return text
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
'''
boot_secs = 0
res = __salt__['cmd.run_all']('ps -o etime= -p 1')
if res['retcode'] > 0:
raise CommandExecutionError('Unable to find boot_time for pid 1.')
bt_time = res['stdout']
days = bt_time.split('-')
hms = days[1].split(':')
boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2])
return boot_secs
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
'5-min': load_avg[2].strip(','),
'15-min': load_avg[3]}
def _aix_nproc():
'''
Return the maximun number of PROCESSES allowed per user on AIX
'''
nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split()
return _number(nprocs[1])
def procs():
'''
Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs
'''
# Get the user, pid and cmd
ret = {}
uind = 0
pind = 0
cind = 0
plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines()
guide = plines.pop(0).split()
if 'USER' in guide:
uind = guide.index('USER')
elif 'UID' in guide:
uind = guide.index('UID')
if 'PID' in guide:
pind = guide.index('PID')
if 'COMMAND' in guide:
cind = guide.index('COMMAND')
elif 'CMD' in guide:
cind = guide.index('CMD')
for line in plines:
if not line:
continue
comps = line.split()
ret[comps[pind]] = {'user': comps[uind],
'cmd': ' '.join(comps[cind:])}
return ret
def custom():
'''
Return a custom composite of status data and info for this minion,
based on the minion config file. An example config like might be::
status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ]
Where status refers to status.py, cpustats is the function
where we get our data, and custom is this function It is followed
by a list of keys that we want returned.
This function is meant to replace all_status(), which returns
anything and everything, which we probably don't want.
By default, nothing is returned. Warning: Depending on what you
include, there can be a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.custom
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
for key, val in six.iteritems(conf):
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123
for item in val:
ret[item] = vals[item]
return ret
def uptime():
'''
Return the uptime for this system.
.. versionchanged:: 2015.8.9
The uptime function was changed to return a dictionary of easy-to-read
key/value pairs containing uptime information, instead of the output
from a ``cmd.run`` call.
.. versionchanged:: 2016.11.0
Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.uptime
'''
curr_seconds = time.time()
# Get uptime in seconds
if salt.utils.platform.is_linux():
ut_path = "/proc/uptime"
if not os.path.exists(ut_path):
raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path))
with salt.utils.files.fopen(ut_path) as rfh:
seconds = int(float(rfh.read().split()[0]))
elif salt.utils.platform.is_sunos():
# note: some flavors/versions report the host uptime inside a zone
# https://support.oracle.com/epmos/faces/BugDisplay?id=15611584
res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')
if res['retcode'] > 0:
raise CommandExecutionError('The boot_time kstat was not found.')
seconds = int(curr_seconds - int(res['stdout'].split()[-1]))
elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
seconds = int(curr_seconds - int(bt_data))
elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():
# format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '')
uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])
seconds = int(curr_seconds - uptime['sec'])
elif salt.utils.platform.is_aix():
seconds = _get_boot_time_aix()
else:
return __salt__['cmd.run']('uptime')
# Setup datetime and timedelta objects
boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)
curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)
up_time = curr_time - boot_time
# Construct return information
ut_ret = {
'seconds': seconds,
'since_iso': boot_time.isoformat(),
'since_t': int(curr_seconds - seconds),
'days': up_time.days,
'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),
}
if salt.utils.path.which('who'):
who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s
ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))
return ut_ret
def loadavg():
'''
Return the load averages for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.loadavg
:raises CommandExecutionError: If the system cannot report loadaverages to Python
'''
if __grains__['kernel'] == 'AIX':
return _aix_loadavg()
try:
load_avg = os.getloadavg()
except AttributeError:
# Some UNIX-based operating systems do not have os.getloadavg()
raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')
return {'1-min': load_avg[0],
'5-min': load_avg[1],
'15-min': load_avg[2]}
def cpustats():
'''
Return the CPU stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpustats
'''
def linux_cpustats():
'''
linux specific implementation of cpustats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == 'cpu':
ret[comps[0]] = {'idle': _number(comps[4]),
'iowait': _number(comps[5]),
'irq': _number(comps[6]),
'nice': _number(comps[2]),
'softirq': _number(comps[7]),
'steal': _number(comps[8]),
'system': _number(comps[3]),
'user': _number(comps[1])}
elif comps[0] == 'intr':
ret[comps[0]] = {'total': _number(comps[1]),
'irqs': [_number(x) for x in comps[2:]]}
elif comps[0] == 'softirq':
ret[comps[0]] = {'total': _number(comps[1]),
'softirqs': [_number(x) for x in comps[2:]]}
else:
ret[comps[0]] = _number(comps[1])
return ret
def freebsd_cpustats():
'''
freebsd specific implementation of cpustats
'''
vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
vm0 = vmstat[0].split()
cpu0loc = vm0.index('cpu0')
vm1 = vmstat[1].split()
usloc = vm1.index('us')
vm2 = vmstat[2].split()
cpuctr = 0
ret = {}
for cpu in vm0[cpu0loc:]:
ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
cpuctr += 1
return ret
def sunos_cpustats():
'''
sunos specific implementation of cpustats
'''
mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
fields = mpstat[0].split()
ret = {}
for cpu in mpstat:
if cpu.startswith('CPU'):
continue
cpu = cpu.split()
ret[_number(cpu[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
return ret
def aix_cpustats():
'''
AIX specific implementation of cpustats
'''
ret = {}
ret['mpstat'] = []
procn = None
fields = []
for line in __salt__['cmd.run']('mpstat -a').splitlines():
if not line:
continue
procn = len(ret['mpstat'])
if line.startswith('System'):
comps = line.split(':')
ret['mpstat'].append({})
ret['mpstat'][procn]['system'] = {}
cpu_comps = comps[1].split()
for i in range(0, len(cpu_comps)):
cpu_vals = cpu_comps[i].split('=')
ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]
if line.startswith('cpu'):
fields = line.split()
continue
if fields:
cpustat = line.split()
ret[_number(cpustat[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])
return ret
def openbsd_cpustats():
'''
openbsd specific implementation of cpustats
'''
systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
fields = systat[3].split()
ret = {}
for cpu in systat[4:]:
cpu_line = cpu.split()
cpu_idx = cpu_line[0]
ret[cpu_idx] = {}
for idx, field in enumerate(fields[1:]):
ret[cpu_idx][field] = cpu_line[idx+1]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_cpustats,
'FreeBSD': freebsd_cpustats,
'OpenBSD': openbsd_cpustats,
'SunOS': sunos_cpustats,
'AIX': aix_cpustats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''
linux specific implementation of meminfo
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {
'value': comps[1],
}
if len(comps) > 2:
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'''
freebsd specific implementation of meminfo
'''
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
# Special handling for vm.total as it's especially important
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
def aix_meminfo():
'''
AIX specific implementation of meminfo
'''
ret = {}
ret['svmon'] = []
ret['vmstat'] = []
procn = None
fields = []
pagesize_flag = False
for line in __salt__['cmd.run']('svmon -G').splitlines():
# Note: svmon is per-system
# size inuse free pin virtual mmode
#memory 1048576 1039740 8836 285078 474993 Ded
#pg space 917504 2574
#
# work pers clnt other
#pin 248379 0 2107 34592
#in use 474993 0 564747
#
#PageSize PoolSize inuse pgsp pin virtual
#s 4 KB - 666956 2574 60726 102209
#m 64 KB - 23299 0 14022 23299
if not line:
continue
if re.match(r'\s', line):
# assume fields line
fields = line.split()
continue
if line.startswith('memory') or line.startswith('pin'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i + 1:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
continue
if line.startswith('pg space') or line.startswith('in use'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
pg_space = '{0} {1}'.format(comps[0], comps[1])
ret['svmon'][procn][pg_space] = {}
for i in range(0, len(fields)):
if len(comps) > i + 2:
ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
continue
if line.startswith('PageSize'):
fields = line.split()
pagesize_flag = False
continue
if pagesize_flag:
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
continue
for line in __salt__['cmd.run']('vmstat -v').splitlines():
# Note: vmstat is per-system
if not line:
continue
procn = len(ret['vmstat'])
ret['vmstat'].append({})
comps = line.lstrip().split(' ', 1)
ret['vmstat'][procn][comps[1]] = comps[0]
return ret
def openbsd_meminfo():
'''
openbsd specific implementation of meminfo
'''
vmstat = __salt__['cmd.run']('vmstat').splitlines()
# We're only interested in memory and page values which are printed
# as subsequent fields.
fields = ['active virtual pages', 'free list size', 'page faults',
'pages reclaimed', 'pages paged in', 'pages paged out',
'pages freed', 'pages scanned']
data = vmstat[2].split()[2:10]
ret = dict(zip(fields, data))
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_meminfo,
'FreeBSD': freebsd_meminfo,
'OpenBSD': openbsd_meminfo,
'AIX': aix_meminfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def cpuinfo():
'''
.. versionchanged:: 2016.3.2
Return the CPU info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for NetBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpuinfo
'''
def linux_cpuinfo():
'''
linux specific cpuinfo implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
if comps[0] == 'flags':
ret[comps[0]] = comps[1].split()
else:
ret[comps[0]] = comps[1].strip()
return ret
def bsd_cpuinfo():
'''
bsd specific cpuinfo implementation
'''
bsd_cmd = 'sysctl hw.model hw.ncpu'
ret = {}
if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:
sep = '='
else:
sep = ':'
for line in __salt__['cmd.run'](bsd_cmd).splitlines():
if not line:
continue
comps = line.split(sep)
comps[0] = comps[0].strip()
ret[comps[0]] = comps[1].strip()
return ret
def sunos_cpuinfo():
'''
sunos specific cpuinfo implementation
'''
ret = {}
ret['isainfo'] = {}
for line in __salt__['cmd.run']('isainfo -x').splitlines():
# Note: isainfo is per-system and not per-cpu
# Output Example:
#amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu
#i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())
ret['psrinfo'] = []
procn = None
for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():
# Output Example:
#The physical processor has 6 cores and 12 virtual processors (0-5 12-17)
# The core has 2 virtual processors (0 12)
# The core has 2 virtual processors (1 13)
# The core has 2 virtual processors (2 14)
# The core has 2 virtual processors (3 15)
# The core has 2 virtual processors (4 16)
# The core has 2 virtual processors (5 17)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#The physical processor has 6 cores and 12 virtual processors (6-11 18-23)
# The core has 2 virtual processors (6 18)
# The core has 2 virtual processors (7 19)
# The core has 2 virtual processors (8 20)
# The core has 2 virtual processors (9 21)
# The core has 2 virtual processors (10 22)
# The core has 2 virtual processors (11 23)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#
# Output Example 2:
#The physical processor has 4 virtual processors (0-3)
# x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)
# Intel(r) Atom(tm) CPU C2558 @ 2.40GHz
if not line:
continue
if line.startswith('The physical processor'):
procn = len(ret['psrinfo'])
line = line.split()
ret['psrinfo'].append({})
if 'cores' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])
ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])
elif 'virtual' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])
elif line.startswith(' ' * 6): # 3x2 space indent
ret['psrinfo'][procn]['name'] = line.strip()
elif line.startswith(' ' * 4): # 2x2 space indent
line = line.strip().split()
ret['psrinfo'][procn]['vendor'] = line[1][1:]
ret['psrinfo'][procn]['family'] = _number(line[4])
ret['psrinfo'][procn]['model'] = _number(line[6])
ret['psrinfo'][procn]['step'] = _number(line[8])
ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1])
return ret
def aix_cpuinfo():
'''
AIX specific cpuinfo implementation
'''
ret = {}
ret['prtconf'] = []
ret['lparstat'] = []
procn = None
for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#prtconf | grep -i "Processor"
#Processor Type: PowerPC_POWER7
#Processor Implementation Mode: POWER 7
#Processor Version: PV_7_Compat
#Number Of Processors: 2
#Processor Clock Speed: 3000 MHz
# Model Implementation: Multiple Processor, PCI bus
# + proc0 Processor
# + proc4 Processor
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('Processor') or line.startswith('Number'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#CPU Type: 64-bit
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('CPU'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():
# Note: lparstat is per-system and not per-cpu
# Output Example:
#Online Virtual CPUs : 2
#Maximum Virtual CPUs : 2
#Minimum Virtual CPUs : 1
#Maximum Physical CPUs in system : 32
#Active Physical CPUs in system : 32
#Active CPUs in Pool : 32
#Shared Physical CPUs in system : 32
#Physical CPU Percentage : 25.00%
#Desired Virtual CPUs : 2
if not line:
continue
procn = len(ret['lparstat'])
ret['lparstat'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['lparstat'][procn][comps[0]] = comps[1]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_cpuinfo,
'FreeBSD': bsd_cpuinfo,
'NetBSD': bsd_cpuinfo,
'OpenBSD': bsd_cpuinfo,
'SunOS': sunos_cpuinfo,
'AIX': aix_cpuinfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific implementation of diskstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[2]] = {
'major': _number(comps[0]),
'minor': _number(comps[1]),
'device': _number(comps[2]),
'reads_issued': _number(comps[3]),
'reads_merged': _number(comps[4]),
'sectors_read': _number(comps[5]),
'ms_spent_reading': _number(comps[6]),
'writes_completed': _number(comps[7]),
'writes_merged': _number(comps[8]),
'sectors_written': _number(comps[9]),
'ms_spent_writing': _number(comps[10]),
'io_in_progress': _number(comps[11]),
'ms_spent_in_io': _number(comps[12]),
'weighted_ms_spent_in_io': _number(comps[13])
}
return ret
def generic_diskstats():
'''
generic implementation of diskstats
note: freebsd and sunos
'''
ret = {}
iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
header = iostat[1]
for line in iostat[2:]:
comps = line.split()
ret[comps[0]] = {}
for metric, value in zip(header.split()[1:], comps[1:]):
ret[comps[0]][metric] = _number(value)
return ret
def aix_diskstats():
'''
AIX specific implementation of diskstats
'''
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
for line in __salt__['cmd.run']('iostat -dDV').splitlines():
# Note: iostat -dDV is per-system
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk0 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.8 0.0 0.0 0.8
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 2.5 0.3 12.4 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.3 0.2 0.7 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.3 0.0 5.3 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#have new disk
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()
ret[disk_name] = []
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
else:
comps = line.split()
for i in range(0, len(fields)):
if len(comps) > i:
ret[disk_name][procn][disk_mode][fields[i]] = comps[i]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_diskstats,
'FreeBSD': generic_diskstats,
'SunOS': generic_diskstats,
'AIX': aix_diskstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskusage(*args):
'''
Return the disk usage for this minion
Usage::
salt '*' status.diskusage [paths and/or filesystem types]
CLI Example:
.. code-block:: bash
salt '*' status.diskusage # usage for all filesystems
salt '*' status.diskusage / /tmp # usage for / and /tmp
salt '*' status.diskusage ext? # usage for ext[234] filesystems
salt '*' status.diskusage / ext? # usage for / and all ext filesystems
'''
selected = set()
fstypes = set()
if not args:
# select all filesystems
fstypes.add('*')
else:
for arg in args:
if arg.startswith('/'):
# select path
selected.add(arg)
else:
# select fstype
fstypes.add(arg)
if fstypes:
# determine which mount points host the specified fstypes
regex = re.compile(
'|'.join(
fnmatch.translate(fstype).format('(%s)') for fstype in fstypes
)
)
# ifile source of data varies with OS, otherwise all the same
if __grains__['kernel'] == 'Linux':
try:
with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:
ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()
except OSError:
return {}
elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):
ifile = __salt__['cmd.run']('mount -p').splitlines()
else:
raise CommandExecutionError('status.diskusage not yet supported on this platform')
for line in ifile:
comps = line.split()
if __grains__['kernel'] == 'SunOS':
if len(comps) >= 4:
mntpt = comps[2]
fstype = comps[3]
if regex.match(fstype):
selected.add(mntpt)
else:
if len(comps) >= 3:
mntpt = comps[1]
fstype = comps[2]
if regex.match(fstype):
selected.add(mntpt)
# query the filesystems disk usage
ret = {}
for path in selected:
fsstats = os.statvfs(path)
blksz = fsstats.f_bsize
available = fsstats.f_bavail * blksz
total = fsstats.f_blocks * blksz
ret[path] = {"available": available, "total": total}
return ret
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specific implementation of vmstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[0]] = _number(comps[1])
return ret
def generic_vmstats():
'''
generic implementation of vmstats
note: works on FreeBSD, SunOS and OpenBSD (possibly others)
'''
ret = {}
for line in __salt__['cmd.run']('vmstat -s').splitlines():
comps = line.split()
if comps[0].isdigit():
ret[' '.join(comps[1:])] = _number(comps[0].strip())
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_vmstats,
'FreeBSD': generic_vmstats,
'OpenBSD': generic_vmstats,
'SunOS': generic_vmstats,
'AIX': generic_vmstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def nproc():
'''
Return the number of processing units available on this system
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for Darwin, FreeBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.nproc
'''
def linux_nproc():
'''
linux specific implementation of nproc
'''
try:
return _number(__salt__['cmd.run']('nproc').strip())
except ValueError:
return 0
def generic_nproc():
'''
generic implementation of nproc
'''
ncpu_data = __salt__['sysctl.get']('hw.ncpu')
if not ncpu_data:
# We need at least one CPU to run
return 1
else:
return _number(ncpu_data)
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_nproc,
'Darwin': generic_nproc,
'FreeBSD': generic_nproc,
'OpenBSD': generic_nproc,
'AIX': _aix_nproc,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netstats():
'''
Return the network stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.netstats
'''
def linux_netstats():
'''
linux specific netstats implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
headers = ['']
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
else:
headers = comps
return ret
def freebsd_netstats():
return bsd_netstats()
def bsd_netstats():
'''
bsd specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
if line.startswith('\t\t'):
continue # Skip, too detailed
if not line.startswith('\t'):
key = line.split()[0].replace(':', '')
ret[key] = {}
else:
comps = line.split()
if comps[0].isdigit():
ret[key][' '.join(comps[1:])] = comps[0]
return ret
def sunos_netstats():
'''
sunos specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
line = line.replace('=', ' = ').split()
if len(line) > 6:
line.pop(0)
if '=' in line:
if len(line) >= 3:
if line[2].isdigit() or line[2][0] == '-':
line[2] = _number(line[2])
ret[line[0]] = line[2]
if len(line) >= 6:
if line[5].isdigit() or line[5][0] == '-':
line[5] = _number(line[5])
ret[line[3]] = line[5]
return ret
def aix_netstats():
'''
AIX specific netstats implementation
'''
ret = {}
fields = []
procn = None
proto_name = None
for line in __salt__['cmd.run']('netstat -s').splitlines():
if not line:
continue
if not re.match(r'\s', line) and ':' in line:
comps = line.split(':')
proto_name = comps[0]
ret[proto_name] = []
procn = len(ret[proto_name])
ret[proto_name].append({})
continue
else:
comps = line.split()
comps[0] = comps[0].strip()
if comps[0].isdigit():
ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])
else:
continue
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netstats,
'FreeBSD': bsd_netstats,
'OpenBSD': bsd_netstats,
'SunOS': sunos_netstats,
'AIX': aix_netstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def w(): # pylint: disable=C0103
'''
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
'''
def linux_w():
'''
Linux specific implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -fh').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'idle': comps[3],
'jcpu': comps[4],
'login': comps[2],
'pcpu': comps[5],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[6:])}
user_list.append(rec)
return user_list
def bsd_w():
'''
Generic BSD implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -h').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'from': comps[2],
'idle': comps[4],
'login': comps[3],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[5:])}
user_list.append(rec)
return user_list
# dict that returns a function that does the right thing per platform
get_version = {
'Darwin': bsd_w,
'FreeBSD': bsd_w,
'Linux': linux_w,
'OpenBSD': bsd_w,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def all_status():
'''
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
'''
return {'cpuinfo': cpuinfo(),
'cpustats': cpustats(),
'diskstats': diskstats(),
'diskusage': diskusage(),
'loadavg': loadavg(),
'meminfo': meminfo(),
'netdev': netdev(),
'netstats': netstats(),
'uptime': uptime(),
'vmstats': vmstats(),
'w': w()}
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
'''
cmd = __grains__['ps']
output = __salt__['cmd.run_stdout'](cmd, python_shell=True)
pids = ''
for line in output.splitlines():
if 'status.pid' in line:
continue
if re.search(sig, line):
if pids:
pids += '\n'
pids += line.split()[1]
return pids
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
'''
linux specific implementation of version
'''
try:
with salt.utils.files.fopen('/proc/version', 'r') as fp_:
return salt.utils.stringutils.to_unicode(fp_.read()).strip()
except IOError:
return {}
def bsd_version():
'''
bsd specific implementation of version
'''
return __salt__['cmd.run']('sysctl -n kern.version')
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_version,
'FreeBSD': bsd_version,
'OpenBSD': bsd_version,
'AIX': lambda: __salt__['cmd.run']('oslevel -s'),
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def master(master=None, connected=True):
'''
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
master_ips = None
if master:
master_ips = salt.utils.network.host_to_ips(master)
if not master_ips:
return
master_connection_status = False
port = __salt__['config.get']('publish_port', default=4505)
connected_ips = salt.utils.network.remote_port_tcp(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
def ping_master(master):
'''
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
'''
if master is None or master == '':
return False
opts = copy.deepcopy(__opts__)
opts['master'] = master
if 'master_ip' in opts: # avoid 'master ip changed' warning
del opts['master_ip']
opts.update(salt.minion.prep_ip_port(opts))
try:
opts.update(salt.minion.resolve_dns(opts, fallback=False))
except Exception:
return False
timeout = opts.get('auth_timeout', 60)
load = {'cmd': 'ping'}
result = False
channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear')
try:
payload = channel.send(load, tries=0, timeout=timeout)
result = True
except Exception as e:
pass
if result:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
event.fire_event({'master': master}, salt.minion.master_event(type='failback'))
return result
def proxy_reconnect(proxy_name, opts=None):
'''
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
'''
if not opts:
opts = __opts__
if 'proxy' not in opts:
return False # fail
proxy_keepalive_fn = proxy_name+'.alive'
if proxy_keepalive_fn not in __proxy__:
return False # fail
is_alive = __proxy__[proxy_keepalive_fn](opts)
if not is_alive:
minion_id = opts.get('proxyid', '') or opts.get('id', '')
log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name)
__proxy__[proxy_name+'.shutdown'](opts) # safely close connection
__proxy__[proxy_name+'.init'](opts) # reopen connection
log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name)
return True # success
def time_(format='%A, %d. %B %Y %I:%M%p'):
'''
.. versionadded:: 2016.3.0
Return the current time on the minion,
formatted based on the format parameter.
Default date format: Monday, 27. July 2015 07:55AM
CLI Example:
.. code-block:: bash
salt '*' status.time
salt '*' status.time '%s'
'''
dt = datetime.datetime.today()
return dt.strftime(format)
|
saltstack/salt
|
salt/modules/status.py
|
w
|
python
|
def w(): # pylint: disable=C0103
'''
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
'''
def linux_w():
'''
Linux specific implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -fh').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'idle': comps[3],
'jcpu': comps[4],
'login': comps[2],
'pcpu': comps[5],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[6:])}
user_list.append(rec)
return user_list
def bsd_w():
'''
Generic BSD implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -h').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'from': comps[2],
'idle': comps[4],
'login': comps[3],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[5:])}
user_list.append(rec)
return user_list
# dict that returns a function that does the right thing per platform
get_version = {
'Darwin': bsd_w,
'FreeBSD': bsd_w,
'Linux': linux_w,
'OpenBSD': bsd_w,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
|
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1434-L1492
| null |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import logging
import fnmatch
import collections
import copy
import time
import logging
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.config
import salt.minion
import salt.utils.event
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__file__)
__virtualname__ = 'status'
__opts__ = {}
# Don't shadow built-in's.
__func_alias__ = {
'time_': 'time'
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Not all functions supported by Windows
'''
if salt.utils.platform.is_windows():
return False, 'Windows platform is not supported by this module'
return __virtualname__
def _number(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
if text.isdigit():
return int(text)
try:
return float(text)
except ValueError:
return text
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
'''
boot_secs = 0
res = __salt__['cmd.run_all']('ps -o etime= -p 1')
if res['retcode'] > 0:
raise CommandExecutionError('Unable to find boot_time for pid 1.')
bt_time = res['stdout']
days = bt_time.split('-')
hms = days[1].split(':')
boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2])
return boot_secs
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
'5-min': load_avg[2].strip(','),
'15-min': load_avg[3]}
def _aix_nproc():
'''
Return the maximun number of PROCESSES allowed per user on AIX
'''
nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split()
return _number(nprocs[1])
def procs():
'''
Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs
'''
# Get the user, pid and cmd
ret = {}
uind = 0
pind = 0
cind = 0
plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines()
guide = plines.pop(0).split()
if 'USER' in guide:
uind = guide.index('USER')
elif 'UID' in guide:
uind = guide.index('UID')
if 'PID' in guide:
pind = guide.index('PID')
if 'COMMAND' in guide:
cind = guide.index('COMMAND')
elif 'CMD' in guide:
cind = guide.index('CMD')
for line in plines:
if not line:
continue
comps = line.split()
ret[comps[pind]] = {'user': comps[uind],
'cmd': ' '.join(comps[cind:])}
return ret
def custom():
'''
Return a custom composite of status data and info for this minion,
based on the minion config file. An example config like might be::
status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ]
Where status refers to status.py, cpustats is the function
where we get our data, and custom is this function It is followed
by a list of keys that we want returned.
This function is meant to replace all_status(), which returns
anything and everything, which we probably don't want.
By default, nothing is returned. Warning: Depending on what you
include, there can be a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.custom
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
for key, val in six.iteritems(conf):
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123
for item in val:
ret[item] = vals[item]
return ret
def uptime():
'''
Return the uptime for this system.
.. versionchanged:: 2015.8.9
The uptime function was changed to return a dictionary of easy-to-read
key/value pairs containing uptime information, instead of the output
from a ``cmd.run`` call.
.. versionchanged:: 2016.11.0
Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.uptime
'''
curr_seconds = time.time()
# Get uptime in seconds
if salt.utils.platform.is_linux():
ut_path = "/proc/uptime"
if not os.path.exists(ut_path):
raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path))
with salt.utils.files.fopen(ut_path) as rfh:
seconds = int(float(rfh.read().split()[0]))
elif salt.utils.platform.is_sunos():
# note: some flavors/versions report the host uptime inside a zone
# https://support.oracle.com/epmos/faces/BugDisplay?id=15611584
res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')
if res['retcode'] > 0:
raise CommandExecutionError('The boot_time kstat was not found.')
seconds = int(curr_seconds - int(res['stdout'].split()[-1]))
elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
seconds = int(curr_seconds - int(bt_data))
elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():
# format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '')
uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])
seconds = int(curr_seconds - uptime['sec'])
elif salt.utils.platform.is_aix():
seconds = _get_boot_time_aix()
else:
return __salt__['cmd.run']('uptime')
# Setup datetime and timedelta objects
boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)
curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)
up_time = curr_time - boot_time
# Construct return information
ut_ret = {
'seconds': seconds,
'since_iso': boot_time.isoformat(),
'since_t': int(curr_seconds - seconds),
'days': up_time.days,
'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),
}
if salt.utils.path.which('who'):
who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s
ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))
return ut_ret
def loadavg():
'''
Return the load averages for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.loadavg
:raises CommandExecutionError: If the system cannot report loadaverages to Python
'''
if __grains__['kernel'] == 'AIX':
return _aix_loadavg()
try:
load_avg = os.getloadavg()
except AttributeError:
# Some UNIX-based operating systems do not have os.getloadavg()
raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')
return {'1-min': load_avg[0],
'5-min': load_avg[1],
'15-min': load_avg[2]}
def cpustats():
'''
Return the CPU stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpustats
'''
def linux_cpustats():
'''
linux specific implementation of cpustats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == 'cpu':
ret[comps[0]] = {'idle': _number(comps[4]),
'iowait': _number(comps[5]),
'irq': _number(comps[6]),
'nice': _number(comps[2]),
'softirq': _number(comps[7]),
'steal': _number(comps[8]),
'system': _number(comps[3]),
'user': _number(comps[1])}
elif comps[0] == 'intr':
ret[comps[0]] = {'total': _number(comps[1]),
'irqs': [_number(x) for x in comps[2:]]}
elif comps[0] == 'softirq':
ret[comps[0]] = {'total': _number(comps[1]),
'softirqs': [_number(x) for x in comps[2:]]}
else:
ret[comps[0]] = _number(comps[1])
return ret
def freebsd_cpustats():
'''
freebsd specific implementation of cpustats
'''
vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
vm0 = vmstat[0].split()
cpu0loc = vm0.index('cpu0')
vm1 = vmstat[1].split()
usloc = vm1.index('us')
vm2 = vmstat[2].split()
cpuctr = 0
ret = {}
for cpu in vm0[cpu0loc:]:
ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
cpuctr += 1
return ret
def sunos_cpustats():
'''
sunos specific implementation of cpustats
'''
mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
fields = mpstat[0].split()
ret = {}
for cpu in mpstat:
if cpu.startswith('CPU'):
continue
cpu = cpu.split()
ret[_number(cpu[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
return ret
def aix_cpustats():
'''
AIX specific implementation of cpustats
'''
ret = {}
ret['mpstat'] = []
procn = None
fields = []
for line in __salt__['cmd.run']('mpstat -a').splitlines():
if not line:
continue
procn = len(ret['mpstat'])
if line.startswith('System'):
comps = line.split(':')
ret['mpstat'].append({})
ret['mpstat'][procn]['system'] = {}
cpu_comps = comps[1].split()
for i in range(0, len(cpu_comps)):
cpu_vals = cpu_comps[i].split('=')
ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]
if line.startswith('cpu'):
fields = line.split()
continue
if fields:
cpustat = line.split()
ret[_number(cpustat[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])
return ret
def openbsd_cpustats():
'''
openbsd specific implementation of cpustats
'''
systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
fields = systat[3].split()
ret = {}
for cpu in systat[4:]:
cpu_line = cpu.split()
cpu_idx = cpu_line[0]
ret[cpu_idx] = {}
for idx, field in enumerate(fields[1:]):
ret[cpu_idx][field] = cpu_line[idx+1]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_cpustats,
'FreeBSD': freebsd_cpustats,
'OpenBSD': openbsd_cpustats,
'SunOS': sunos_cpustats,
'AIX': aix_cpustats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''
linux specific implementation of meminfo
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {
'value': comps[1],
}
if len(comps) > 2:
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'''
freebsd specific implementation of meminfo
'''
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
# Special handling for vm.total as it's especially important
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
def aix_meminfo():
'''
AIX specific implementation of meminfo
'''
ret = {}
ret['svmon'] = []
ret['vmstat'] = []
procn = None
fields = []
pagesize_flag = False
for line in __salt__['cmd.run']('svmon -G').splitlines():
# Note: svmon is per-system
# size inuse free pin virtual mmode
#memory 1048576 1039740 8836 285078 474993 Ded
#pg space 917504 2574
#
# work pers clnt other
#pin 248379 0 2107 34592
#in use 474993 0 564747
#
#PageSize PoolSize inuse pgsp pin virtual
#s 4 KB - 666956 2574 60726 102209
#m 64 KB - 23299 0 14022 23299
if not line:
continue
if re.match(r'\s', line):
# assume fields line
fields = line.split()
continue
if line.startswith('memory') or line.startswith('pin'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i + 1:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
continue
if line.startswith('pg space') or line.startswith('in use'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
pg_space = '{0} {1}'.format(comps[0], comps[1])
ret['svmon'][procn][pg_space] = {}
for i in range(0, len(fields)):
if len(comps) > i + 2:
ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
continue
if line.startswith('PageSize'):
fields = line.split()
pagesize_flag = False
continue
if pagesize_flag:
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
continue
for line in __salt__['cmd.run']('vmstat -v').splitlines():
# Note: vmstat is per-system
if not line:
continue
procn = len(ret['vmstat'])
ret['vmstat'].append({})
comps = line.lstrip().split(' ', 1)
ret['vmstat'][procn][comps[1]] = comps[0]
return ret
def openbsd_meminfo():
'''
openbsd specific implementation of meminfo
'''
vmstat = __salt__['cmd.run']('vmstat').splitlines()
# We're only interested in memory and page values which are printed
# as subsequent fields.
fields = ['active virtual pages', 'free list size', 'page faults',
'pages reclaimed', 'pages paged in', 'pages paged out',
'pages freed', 'pages scanned']
data = vmstat[2].split()[2:10]
ret = dict(zip(fields, data))
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_meminfo,
'FreeBSD': freebsd_meminfo,
'OpenBSD': openbsd_meminfo,
'AIX': aix_meminfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def cpuinfo():
'''
.. versionchanged:: 2016.3.2
Return the CPU info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for NetBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpuinfo
'''
def linux_cpuinfo():
'''
linux specific cpuinfo implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
if comps[0] == 'flags':
ret[comps[0]] = comps[1].split()
else:
ret[comps[0]] = comps[1].strip()
return ret
def bsd_cpuinfo():
'''
bsd specific cpuinfo implementation
'''
bsd_cmd = 'sysctl hw.model hw.ncpu'
ret = {}
if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:
sep = '='
else:
sep = ':'
for line in __salt__['cmd.run'](bsd_cmd).splitlines():
if not line:
continue
comps = line.split(sep)
comps[0] = comps[0].strip()
ret[comps[0]] = comps[1].strip()
return ret
def sunos_cpuinfo():
'''
sunos specific cpuinfo implementation
'''
ret = {}
ret['isainfo'] = {}
for line in __salt__['cmd.run']('isainfo -x').splitlines():
# Note: isainfo is per-system and not per-cpu
# Output Example:
#amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu
#i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())
ret['psrinfo'] = []
procn = None
for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():
# Output Example:
#The physical processor has 6 cores and 12 virtual processors (0-5 12-17)
# The core has 2 virtual processors (0 12)
# The core has 2 virtual processors (1 13)
# The core has 2 virtual processors (2 14)
# The core has 2 virtual processors (3 15)
# The core has 2 virtual processors (4 16)
# The core has 2 virtual processors (5 17)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#The physical processor has 6 cores and 12 virtual processors (6-11 18-23)
# The core has 2 virtual processors (6 18)
# The core has 2 virtual processors (7 19)
# The core has 2 virtual processors (8 20)
# The core has 2 virtual processors (9 21)
# The core has 2 virtual processors (10 22)
# The core has 2 virtual processors (11 23)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#
# Output Example 2:
#The physical processor has 4 virtual processors (0-3)
# x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)
# Intel(r) Atom(tm) CPU C2558 @ 2.40GHz
if not line:
continue
if line.startswith('The physical processor'):
procn = len(ret['psrinfo'])
line = line.split()
ret['psrinfo'].append({})
if 'cores' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])
ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])
elif 'virtual' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])
elif line.startswith(' ' * 6): # 3x2 space indent
ret['psrinfo'][procn]['name'] = line.strip()
elif line.startswith(' ' * 4): # 2x2 space indent
line = line.strip().split()
ret['psrinfo'][procn]['vendor'] = line[1][1:]
ret['psrinfo'][procn]['family'] = _number(line[4])
ret['psrinfo'][procn]['model'] = _number(line[6])
ret['psrinfo'][procn]['step'] = _number(line[8])
ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1])
return ret
def aix_cpuinfo():
'''
AIX specific cpuinfo implementation
'''
ret = {}
ret['prtconf'] = []
ret['lparstat'] = []
procn = None
for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#prtconf | grep -i "Processor"
#Processor Type: PowerPC_POWER7
#Processor Implementation Mode: POWER 7
#Processor Version: PV_7_Compat
#Number Of Processors: 2
#Processor Clock Speed: 3000 MHz
# Model Implementation: Multiple Processor, PCI bus
# + proc0 Processor
# + proc4 Processor
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('Processor') or line.startswith('Number'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#CPU Type: 64-bit
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('CPU'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():
# Note: lparstat is per-system and not per-cpu
# Output Example:
#Online Virtual CPUs : 2
#Maximum Virtual CPUs : 2
#Minimum Virtual CPUs : 1
#Maximum Physical CPUs in system : 32
#Active Physical CPUs in system : 32
#Active CPUs in Pool : 32
#Shared Physical CPUs in system : 32
#Physical CPU Percentage : 25.00%
#Desired Virtual CPUs : 2
if not line:
continue
procn = len(ret['lparstat'])
ret['lparstat'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['lparstat'][procn][comps[0]] = comps[1]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_cpuinfo,
'FreeBSD': bsd_cpuinfo,
'NetBSD': bsd_cpuinfo,
'OpenBSD': bsd_cpuinfo,
'SunOS': sunos_cpuinfo,
'AIX': aix_cpuinfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific implementation of diskstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[2]] = {
'major': _number(comps[0]),
'minor': _number(comps[1]),
'device': _number(comps[2]),
'reads_issued': _number(comps[3]),
'reads_merged': _number(comps[4]),
'sectors_read': _number(comps[5]),
'ms_spent_reading': _number(comps[6]),
'writes_completed': _number(comps[7]),
'writes_merged': _number(comps[8]),
'sectors_written': _number(comps[9]),
'ms_spent_writing': _number(comps[10]),
'io_in_progress': _number(comps[11]),
'ms_spent_in_io': _number(comps[12]),
'weighted_ms_spent_in_io': _number(comps[13])
}
return ret
def generic_diskstats():
'''
generic implementation of diskstats
note: freebsd and sunos
'''
ret = {}
iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
header = iostat[1]
for line in iostat[2:]:
comps = line.split()
ret[comps[0]] = {}
for metric, value in zip(header.split()[1:], comps[1:]):
ret[comps[0]][metric] = _number(value)
return ret
def aix_diskstats():
'''
AIX specific implementation of diskstats
'''
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
for line in __salt__['cmd.run']('iostat -dDV').splitlines():
# Note: iostat -dDV is per-system
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk0 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.8 0.0 0.0 0.8
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 2.5 0.3 12.4 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.3 0.2 0.7 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.3 0.0 5.3 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#have new disk
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()
ret[disk_name] = []
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
else:
comps = line.split()
for i in range(0, len(fields)):
if len(comps) > i:
ret[disk_name][procn][disk_mode][fields[i]] = comps[i]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_diskstats,
'FreeBSD': generic_diskstats,
'SunOS': generic_diskstats,
'AIX': aix_diskstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskusage(*args):
'''
Return the disk usage for this minion
Usage::
salt '*' status.diskusage [paths and/or filesystem types]
CLI Example:
.. code-block:: bash
salt '*' status.diskusage # usage for all filesystems
salt '*' status.diskusage / /tmp # usage for / and /tmp
salt '*' status.diskusage ext? # usage for ext[234] filesystems
salt '*' status.diskusage / ext? # usage for / and all ext filesystems
'''
selected = set()
fstypes = set()
if not args:
# select all filesystems
fstypes.add('*')
else:
for arg in args:
if arg.startswith('/'):
# select path
selected.add(arg)
else:
# select fstype
fstypes.add(arg)
if fstypes:
# determine which mount points host the specified fstypes
regex = re.compile(
'|'.join(
fnmatch.translate(fstype).format('(%s)') for fstype in fstypes
)
)
# ifile source of data varies with OS, otherwise all the same
if __grains__['kernel'] == 'Linux':
try:
with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:
ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()
except OSError:
return {}
elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):
ifile = __salt__['cmd.run']('mount -p').splitlines()
else:
raise CommandExecutionError('status.diskusage not yet supported on this platform')
for line in ifile:
comps = line.split()
if __grains__['kernel'] == 'SunOS':
if len(comps) >= 4:
mntpt = comps[2]
fstype = comps[3]
if regex.match(fstype):
selected.add(mntpt)
else:
if len(comps) >= 3:
mntpt = comps[1]
fstype = comps[2]
if regex.match(fstype):
selected.add(mntpt)
# query the filesystems disk usage
ret = {}
for path in selected:
fsstats = os.statvfs(path)
blksz = fsstats.f_bsize
available = fsstats.f_bavail * blksz
total = fsstats.f_blocks * blksz
ret[path] = {"available": available, "total": total}
return ret
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specific implementation of vmstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[0]] = _number(comps[1])
return ret
def generic_vmstats():
'''
generic implementation of vmstats
note: works on FreeBSD, SunOS and OpenBSD (possibly others)
'''
ret = {}
for line in __salt__['cmd.run']('vmstat -s').splitlines():
comps = line.split()
if comps[0].isdigit():
ret[' '.join(comps[1:])] = _number(comps[0].strip())
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_vmstats,
'FreeBSD': generic_vmstats,
'OpenBSD': generic_vmstats,
'SunOS': generic_vmstats,
'AIX': generic_vmstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def nproc():
'''
Return the number of processing units available on this system
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for Darwin, FreeBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.nproc
'''
def linux_nproc():
'''
linux specific implementation of nproc
'''
try:
return _number(__salt__['cmd.run']('nproc').strip())
except ValueError:
return 0
def generic_nproc():
'''
generic implementation of nproc
'''
ncpu_data = __salt__['sysctl.get']('hw.ncpu')
if not ncpu_data:
# We need at least one CPU to run
return 1
else:
return _number(ncpu_data)
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_nproc,
'Darwin': generic_nproc,
'FreeBSD': generic_nproc,
'OpenBSD': generic_nproc,
'AIX': _aix_nproc,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netstats():
'''
Return the network stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.netstats
'''
def linux_netstats():
'''
linux specific netstats implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
headers = ['']
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
else:
headers = comps
return ret
def freebsd_netstats():
return bsd_netstats()
def bsd_netstats():
'''
bsd specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
if line.startswith('\t\t'):
continue # Skip, too detailed
if not line.startswith('\t'):
key = line.split()[0].replace(':', '')
ret[key] = {}
else:
comps = line.split()
if comps[0].isdigit():
ret[key][' '.join(comps[1:])] = comps[0]
return ret
def sunos_netstats():
'''
sunos specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
line = line.replace('=', ' = ').split()
if len(line) > 6:
line.pop(0)
if '=' in line:
if len(line) >= 3:
if line[2].isdigit() or line[2][0] == '-':
line[2] = _number(line[2])
ret[line[0]] = line[2]
if len(line) >= 6:
if line[5].isdigit() or line[5][0] == '-':
line[5] = _number(line[5])
ret[line[3]] = line[5]
return ret
def aix_netstats():
'''
AIX specific netstats implementation
'''
ret = {}
fields = []
procn = None
proto_name = None
for line in __salt__['cmd.run']('netstat -s').splitlines():
if not line:
continue
if not re.match(r'\s', line) and ':' in line:
comps = line.split(':')
proto_name = comps[0]
ret[proto_name] = []
procn = len(ret[proto_name])
ret[proto_name].append({})
continue
else:
comps = line.split()
comps[0] = comps[0].strip()
if comps[0].isdigit():
ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])
else:
continue
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netstats,
'FreeBSD': bsd_netstats,
'OpenBSD': bsd_netstats,
'SunOS': sunos_netstats,
'AIX': aix_netstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific implementation of netdev
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
if line.find(':') < 0:
continue
comps = line.split()
# Fix lines like eth0:9999..'
comps[0] = line.split(':')[0].strip()
# Support lines both like eth0:999 and eth0: 9999
comps.insert(1, line.split(':')[1].strip().split()[0])
ret[comps[0]] = {'iface': comps[0],
'rx_bytes': _number(comps[2]),
'rx_compressed': _number(comps[8]),
'rx_drop': _number(comps[5]),
'rx_errs': _number(comps[4]),
'rx_fifo': _number(comps[6]),
'rx_frame': _number(comps[7]),
'rx_multicast': _number(comps[9]),
'rx_packets': _number(comps[3]),
'tx_bytes': _number(comps[10]),
'tx_carrier': _number(comps[16]),
'tx_colls': _number(comps[15]),
'tx_compressed': _number(comps[17]),
'tx_drop': _number(comps[13]),
'tx_errs': _number(comps[12]),
'tx_fifo': _number(comps[14]),
'tx_packets': _number(comps[11])}
return ret
def freebsd_netdev():
'''
freebsd specific implementation of netdev
'''
_dict_tree = lambda: collections.defaultdict(_dict_tree)
ret = _dict_tree()
netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()
netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]
header = netstat[0].split()
for line in netstat[1:]:
comps = line.split()
for i in range(4, 13): # The columns we want
ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])
return ret
def sunos_netdev():
'''
sunos specific implementation of netdev
'''
ret = {}
##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:
# fetch device info
netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()
# prepare data
netstat_ipv4[0] = netstat_ipv4[0].split()
netstat_ipv4[1] = netstat_ipv4[1].split()
netstat_ipv6[0] = netstat_ipv6[0].split()
netstat_ipv6[1] = netstat_ipv6[1].split()
# add data
ret[dev] = {}
for i in range(len(netstat_ipv4[0])-1):
if netstat_ipv4[0][i] == 'Name':
continue
if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]
else:
ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])
for i in range(len(netstat_ipv6[0])-1):
if netstat_ipv6[0][i] == 'Name':
continue
if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]
else:
ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])
return ret
def aix_netdev():
'''
AIX specific implementation of netdev
'''
ret = {}
fields = []
procn = None
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():
# fetch device info
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0
#en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0
netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()
# add data
ret[dev] = []
for line in netstat_ipv4:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv4'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv4'][fields[i]] = comps[i]
for line in netstat_ipv6:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv6'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv6'][fields[i]] = comps[i]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netdev,
'FreeBSD': freebsd_netdev,
'SunOS': sunos_netdev,
'AIX': aix_netdev,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def all_status():
'''
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
'''
return {'cpuinfo': cpuinfo(),
'cpustats': cpustats(),
'diskstats': diskstats(),
'diskusage': diskusage(),
'loadavg': loadavg(),
'meminfo': meminfo(),
'netdev': netdev(),
'netstats': netstats(),
'uptime': uptime(),
'vmstats': vmstats(),
'w': w()}
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
'''
cmd = __grains__['ps']
output = __salt__['cmd.run_stdout'](cmd, python_shell=True)
pids = ''
for line in output.splitlines():
if 'status.pid' in line:
continue
if re.search(sig, line):
if pids:
pids += '\n'
pids += line.split()[1]
return pids
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
'''
linux specific implementation of version
'''
try:
with salt.utils.files.fopen('/proc/version', 'r') as fp_:
return salt.utils.stringutils.to_unicode(fp_.read()).strip()
except IOError:
return {}
def bsd_version():
'''
bsd specific implementation of version
'''
return __salt__['cmd.run']('sysctl -n kern.version')
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_version,
'FreeBSD': bsd_version,
'OpenBSD': bsd_version,
'AIX': lambda: __salt__['cmd.run']('oslevel -s'),
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def master(master=None, connected=True):
'''
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
master_ips = None
if master:
master_ips = salt.utils.network.host_to_ips(master)
if not master_ips:
return
master_connection_status = False
port = __salt__['config.get']('publish_port', default=4505)
connected_ips = salt.utils.network.remote_port_tcp(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
def ping_master(master):
'''
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
'''
if master is None or master == '':
return False
opts = copy.deepcopy(__opts__)
opts['master'] = master
if 'master_ip' in opts: # avoid 'master ip changed' warning
del opts['master_ip']
opts.update(salt.minion.prep_ip_port(opts))
try:
opts.update(salt.minion.resolve_dns(opts, fallback=False))
except Exception:
return False
timeout = opts.get('auth_timeout', 60)
load = {'cmd': 'ping'}
result = False
channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear')
try:
payload = channel.send(load, tries=0, timeout=timeout)
result = True
except Exception as e:
pass
if result:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
event.fire_event({'master': master}, salt.minion.master_event(type='failback'))
return result
def proxy_reconnect(proxy_name, opts=None):
'''
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
'''
if not opts:
opts = __opts__
if 'proxy' not in opts:
return False # fail
proxy_keepalive_fn = proxy_name+'.alive'
if proxy_keepalive_fn not in __proxy__:
return False # fail
is_alive = __proxy__[proxy_keepalive_fn](opts)
if not is_alive:
minion_id = opts.get('proxyid', '') or opts.get('id', '')
log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name)
__proxy__[proxy_name+'.shutdown'](opts) # safely close connection
__proxy__[proxy_name+'.init'](opts) # reopen connection
log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name)
return True # success
def time_(format='%A, %d. %B %Y %I:%M%p'):
'''
.. versionadded:: 2016.3.0
Return the current time on the minion,
formatted based on the format parameter.
Default date format: Monday, 27. July 2015 07:55AM
CLI Example:
.. code-block:: bash
salt '*' status.time
salt '*' status.time '%s'
'''
dt = datetime.datetime.today()
return dt.strftime(format)
|
saltstack/salt
|
salt/modules/status.py
|
all_status
|
python
|
def all_status():
'''
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
'''
return {'cpuinfo': cpuinfo(),
'cpustats': cpustats(),
'diskstats': diskstats(),
'diskusage': diskusage(),
'loadavg': loadavg(),
'meminfo': meminfo(),
'netdev': netdev(),
'netstats': netstats(),
'uptime': uptime(),
'vmstats': vmstats(),
'w': w()}
|
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1495-L1516
|
[
"def w(): # pylint: disable=C0103\n '''\n Return a list of logged in users for this minion, using the w command\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.w\n '''\n def linux_w():\n '''\n Linux specific implementation for w\n '''\n user_list = []\n users = __salt__['cmd.run']('w -fh').splitlines()\n for row in users:\n if not row:\n continue\n comps = row.split()\n rec = {'idle': comps[3],\n 'jcpu': comps[4],\n 'login': comps[2],\n 'pcpu': comps[5],\n 'tty': comps[1],\n 'user': comps[0],\n 'what': ' '.join(comps[6:])}\n user_list.append(rec)\n return user_list\n\n def bsd_w():\n '''\n Generic BSD implementation for w\n '''\n user_list = []\n users = __salt__['cmd.run']('w -h').splitlines()\n for row in users:\n if not row:\n continue\n comps = row.split()\n rec = {'from': comps[2],\n 'idle': comps[4],\n 'login': comps[3],\n 'tty': comps[1],\n 'user': comps[0],\n 'what': ' '.join(comps[5:])}\n user_list.append(rec)\n return user_list\n\n # dict that returns a function that does the right thing per platform\n get_version = {\n 'Darwin': bsd_w,\n 'FreeBSD': bsd_w,\n 'Linux': linux_w,\n 'OpenBSD': bsd_w,\n }\n\n errmsg = 'This method is unsupported on the current operating system!'\n return get_version.get(__grains__['kernel'], lambda: errmsg)()\n",
"def loadavg():\n '''\n Return the load averages for this minion\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.loadavg\n\n :raises CommandExecutionError: If the system cannot report loadaverages to Python\n '''\n if __grains__['kernel'] == 'AIX':\n return _aix_loadavg()\n\n try:\n load_avg = os.getloadavg()\n except AttributeError:\n # Some UNIX-based operating systems do not have os.getloadavg()\n raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')\n return {'1-min': load_avg[0],\n '5-min': load_avg[1],\n '15-min': load_avg[2]}\n",
"def cpuinfo():\n '''\n .. versionchanged:: 2016.3.2\n Return the CPU info for this minion\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n .. versionchanged:: 2018.3.0\n Added support for NetBSD and OpenBSD\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.cpuinfo\n '''\n def linux_cpuinfo():\n '''\n linux specific cpuinfo implementation\n '''\n ret = {}\n try:\n with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:\n stats = salt.utils.stringutils.to_unicode(fp_.read())\n except IOError:\n pass\n else:\n for line in stats.splitlines():\n if not line:\n continue\n comps = line.split(':')\n comps[0] = comps[0].strip()\n if comps[0] == 'flags':\n ret[comps[0]] = comps[1].split()\n else:\n ret[comps[0]] = comps[1].strip()\n return ret\n\n def bsd_cpuinfo():\n '''\n bsd specific cpuinfo implementation\n '''\n bsd_cmd = 'sysctl hw.model hw.ncpu'\n ret = {}\n if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:\n sep = '='\n else:\n sep = ':'\n\n for line in __salt__['cmd.run'](bsd_cmd).splitlines():\n if not line:\n continue\n comps = line.split(sep)\n comps[0] = comps[0].strip()\n ret[comps[0]] = comps[1].strip()\n return ret\n\n def sunos_cpuinfo():\n '''\n sunos specific cpuinfo implementation\n '''\n ret = {}\n ret['isainfo'] = {}\n for line in __salt__['cmd.run']('isainfo -x').splitlines():\n # Note: isainfo is per-system and not per-cpu\n # Output Example:\n #amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu\n #i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu\n if not line:\n continue\n comps = line.split(':')\n comps[0] = comps[0].strip()\n ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())\n ret['psrinfo'] = []\n procn = None\n for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():\n # Output Example:\n #The physical processor has 6 cores and 12 virtual processors (0-5 12-17)\n # The core has 2 virtual processors (0 12)\n # The core has 2 virtual processors (1 13)\n # The core has 2 virtual processors (2 14)\n # The core has 2 virtual processors (3 15)\n # The core has 2 virtual processors (4 16)\n # The core has 2 virtual processors (5 17)\n # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)\n # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz\n #The physical processor has 6 cores and 12 virtual processors (6-11 18-23)\n # The core has 2 virtual processors (6 18)\n # The core has 2 virtual processors (7 19)\n # The core has 2 virtual processors (8 20)\n # The core has 2 virtual processors (9 21)\n # The core has 2 virtual processors (10 22)\n # The core has 2 virtual processors (11 23)\n # x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)\n # Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz\n #\n # Output Example 2:\n #The physical processor has 4 virtual processors (0-3)\n # x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)\n # Intel(r) Atom(tm) CPU C2558 @ 2.40GHz\n if not line:\n continue\n if line.startswith('The physical processor'):\n procn = len(ret['psrinfo'])\n line = line.split()\n ret['psrinfo'].append({})\n if 'cores' in line:\n ret['psrinfo'][procn]['topology'] = {}\n ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])\n ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])\n elif 'virtual' in line:\n ret['psrinfo'][procn]['topology'] = {}\n ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])\n elif line.startswith(' ' * 6): # 3x2 space indent\n ret['psrinfo'][procn]['name'] = line.strip()\n elif line.startswith(' ' * 4): # 2x2 space indent\n line = line.strip().split()\n ret['psrinfo'][procn]['vendor'] = line[1][1:]\n ret['psrinfo'][procn]['family'] = _number(line[4])\n ret['psrinfo'][procn]['model'] = _number(line[6])\n ret['psrinfo'][procn]['step'] = _number(line[8])\n ret['psrinfo'][procn]['clock'] = \"{0} {1}\".format(line[10], line[11][:-1])\n return ret\n\n def aix_cpuinfo():\n '''\n AIX specific cpuinfo implementation\n '''\n ret = {}\n ret['prtconf'] = []\n ret['lparstat'] = []\n procn = None\n for line in __salt__['cmd.run']('prtconf | grep -i \"Processor\"', python_shell=True).splitlines():\n # Note: prtconf is per-system and not per-cpu\n # Output Example:\n #prtconf | grep -i \"Processor\"\n #Processor Type: PowerPC_POWER7\n #Processor Implementation Mode: POWER 7\n #Processor Version: PV_7_Compat\n #Number Of Processors: 2\n #Processor Clock Speed: 3000 MHz\n # Model Implementation: Multiple Processor, PCI bus\n # + proc0 Processor\n # + proc4 Processor\n if not line:\n continue\n procn = len(ret['prtconf'])\n if line.startswith('Processor') or line.startswith('Number'):\n ret['prtconf'].append({})\n comps = line.split(':')\n comps[0] = comps[0].rstrip()\n ret['prtconf'][procn][comps[0]] = comps[1]\n else:\n continue\n\n for line in __salt__['cmd.run']('prtconf | grep \"CPU\"', python_shell=True).splitlines():\n # Note: prtconf is per-system and not per-cpu\n # Output Example:\n #CPU Type: 64-bit\n if not line:\n continue\n procn = len(ret['prtconf'])\n if line.startswith('CPU'):\n ret['prtconf'].append({})\n comps = line.split(':')\n comps[0] = comps[0].rstrip()\n ret['prtconf'][procn][comps[0]] = comps[1]\n else:\n continue\n\n for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():\n # Note: lparstat is per-system and not per-cpu\n # Output Example:\n #Online Virtual CPUs : 2\n #Maximum Virtual CPUs : 2\n #Minimum Virtual CPUs : 1\n #Maximum Physical CPUs in system : 32\n #Active Physical CPUs in system : 32\n #Active CPUs in Pool : 32\n #Shared Physical CPUs in system : 32\n #Physical CPU Percentage : 25.00%\n #Desired Virtual CPUs : 2\n if not line:\n continue\n\n procn = len(ret['lparstat'])\n ret['lparstat'].append({})\n comps = line.split(':')\n comps[0] = comps[0].rstrip()\n ret['lparstat'][procn][comps[0]] = comps[1]\n\n return ret\n\n # dict that returns a function that does the right thing per platform\n get_version = {\n 'Linux': linux_cpuinfo,\n 'FreeBSD': bsd_cpuinfo,\n 'NetBSD': bsd_cpuinfo,\n 'OpenBSD': bsd_cpuinfo,\n 'SunOS': sunos_cpuinfo,\n 'AIX': aix_cpuinfo,\n }\n\n errmsg = 'This method is unsupported on the current operating system!'\n return get_version.get(__grains__['kernel'], lambda: errmsg)()\n",
"def netstats():\n '''\n Return the network stats for this minion\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n .. versionchanged:: 2018.3.0\n Added support for OpenBSD\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.netstats\n '''\n def linux_netstats():\n '''\n linux specific netstats implementation\n '''\n ret = {}\n try:\n with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:\n stats = salt.utils.stringutils.to_unicode(fp_.read())\n except IOError:\n pass\n else:\n headers = ['']\n for line in stats.splitlines():\n if not line:\n continue\n comps = line.split()\n if comps[0] == headers[0]:\n index = len(headers) - 1\n row = {}\n for field in range(index):\n if field < 1:\n continue\n else:\n row[headers[field]] = _number(comps[field])\n rowname = headers[0].replace(':', '')\n ret[rowname] = row\n else:\n headers = comps\n return ret\n\n def freebsd_netstats():\n return bsd_netstats()\n\n def bsd_netstats():\n '''\n bsd specific netstats implementation\n '''\n ret = {}\n for line in __salt__['cmd.run']('netstat -s').splitlines():\n if line.startswith('\\t\\t'):\n continue # Skip, too detailed\n if not line.startswith('\\t'):\n key = line.split()[0].replace(':', '')\n ret[key] = {}\n else:\n comps = line.split()\n if comps[0].isdigit():\n ret[key][' '.join(comps[1:])] = comps[0]\n return ret\n\n def sunos_netstats():\n '''\n sunos specific netstats implementation\n '''\n ret = {}\n for line in __salt__['cmd.run']('netstat -s').splitlines():\n line = line.replace('=', ' = ').split()\n if len(line) > 6:\n line.pop(0)\n if '=' in line:\n if len(line) >= 3:\n if line[2].isdigit() or line[2][0] == '-':\n line[2] = _number(line[2])\n ret[line[0]] = line[2]\n if len(line) >= 6:\n if line[5].isdigit() or line[5][0] == '-':\n line[5] = _number(line[5])\n ret[line[3]] = line[5]\n return ret\n\n def aix_netstats():\n '''\n AIX specific netstats implementation\n '''\n ret = {}\n fields = []\n procn = None\n proto_name = None\n for line in __salt__['cmd.run']('netstat -s').splitlines():\n if not line:\n continue\n\n if not re.match(r'\\s', line) and ':' in line:\n comps = line.split(':')\n proto_name = comps[0]\n ret[proto_name] = []\n procn = len(ret[proto_name])\n ret[proto_name].append({})\n continue\n else:\n comps = line.split()\n comps[0] = comps[0].strip()\n if comps[0].isdigit():\n ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])\n else:\n continue\n\n return ret\n\n # dict that returns a function that does the right thing per platform\n get_version = {\n 'Linux': linux_netstats,\n 'FreeBSD': bsd_netstats,\n 'OpenBSD': bsd_netstats,\n 'SunOS': sunos_netstats,\n 'AIX': aix_netstats,\n }\n\n errmsg = 'This method is unsupported on the current operating system!'\n return get_version.get(__grains__['kernel'], lambda: errmsg)()\n",
"def meminfo():\n '''\n Return the memory info for this minion\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n .. versionchanged:: 2018.3.0\n Added support for OpenBSD\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.meminfo\n '''\n def linux_meminfo():\n '''\n linux specific implementation of meminfo\n '''\n ret = {}\n try:\n with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:\n stats = salt.utils.stringutils.to_unicode(fp_.read())\n except IOError:\n pass\n else:\n for line in stats.splitlines():\n if not line:\n continue\n comps = line.split()\n comps[0] = comps[0].replace(':', '')\n ret[comps[0]] = {\n 'value': comps[1],\n }\n if len(comps) > 2:\n ret[comps[0]]['unit'] = comps[2]\n return ret\n\n def freebsd_meminfo():\n '''\n freebsd specific implementation of meminfo\n '''\n sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()\n sysctlvm = [x for x in sysctlvm if x.startswith('vm')]\n sysctlvm = [x.split(':') for x in sysctlvm]\n sysctlvm = [[y.strip() for y in x] for x in sysctlvm]\n sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty\n\n ret = {}\n for line in sysctlvm:\n ret[line[0]] = line[1]\n # Special handling for vm.total as it's especially important\n sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()\n sysctlvmtot = [x for x in sysctlvmtot if x]\n ret['vm.vmtotal'] = sysctlvmtot\n return ret\n\n def aix_meminfo():\n '''\n AIX specific implementation of meminfo\n '''\n ret = {}\n ret['svmon'] = []\n ret['vmstat'] = []\n procn = None\n fields = []\n pagesize_flag = False\n for line in __salt__['cmd.run']('svmon -G').splitlines():\n # Note: svmon is per-system\n # size inuse free pin virtual mmode\n #memory 1048576 1039740 8836 285078 474993 Ded\n #pg space 917504 2574\n #\n # work pers clnt other\n #pin 248379 0 2107 34592\n #in use 474993 0 564747\n #\n #PageSize PoolSize inuse pgsp pin virtual\n #s 4 KB - 666956 2574 60726 102209\n #m 64 KB - 23299 0 14022 23299\n if not line:\n continue\n\n if re.match(r'\\s', line):\n # assume fields line\n fields = line.split()\n continue\n\n if line.startswith('memory') or line.startswith('pin'):\n procn = len(ret['svmon'])\n ret['svmon'].append({})\n comps = line.split()\n ret['svmon'][procn][comps[0]] = {}\n for i in range(0, len(fields)):\n if len(comps) > i + 1:\n ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]\n continue\n\n if line.startswith('pg space') or line.startswith('in use'):\n procn = len(ret['svmon'])\n ret['svmon'].append({})\n comps = line.split()\n pg_space = '{0} {1}'.format(comps[0], comps[1])\n ret['svmon'][procn][pg_space] = {}\n for i in range(0, len(fields)):\n if len(comps) > i + 2:\n ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]\n continue\n\n if line.startswith('PageSize'):\n fields = line.split()\n pagesize_flag = False\n continue\n\n if pagesize_flag:\n procn = len(ret['svmon'])\n ret['svmon'].append({})\n comps = line.split()\n ret['svmon'][procn][comps[0]] = {}\n for i in range(0, len(fields)):\n if len(comps) > i:\n ret['svmon'][procn][comps[0]][fields[i]] = comps[i]\n continue\n\n for line in __salt__['cmd.run']('vmstat -v').splitlines():\n # Note: vmstat is per-system\n if not line:\n continue\n\n procn = len(ret['vmstat'])\n ret['vmstat'].append({})\n comps = line.lstrip().split(' ', 1)\n ret['vmstat'][procn][comps[1]] = comps[0]\n\n return ret\n\n def openbsd_meminfo():\n '''\n openbsd specific implementation of meminfo\n '''\n vmstat = __salt__['cmd.run']('vmstat').splitlines()\n # We're only interested in memory and page values which are printed\n # as subsequent fields.\n fields = ['active virtual pages', 'free list size', 'page faults',\n 'pages reclaimed', 'pages paged in', 'pages paged out',\n 'pages freed', 'pages scanned']\n data = vmstat[2].split()[2:10]\n ret = dict(zip(fields, data))\n return ret\n\n # dict that return a function that does the right thing per platform\n get_version = {\n 'Linux': linux_meminfo,\n 'FreeBSD': freebsd_meminfo,\n 'OpenBSD': openbsd_meminfo,\n 'AIX': aix_meminfo,\n }\n\n errmsg = 'This method is unsupported on the current operating system!'\n return get_version.get(__grains__['kernel'], lambda: errmsg)()\n",
"def diskusage(*args):\n '''\n Return the disk usage for this minion\n\n Usage::\n\n salt '*' status.diskusage [paths and/or filesystem types]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.diskusage # usage for all filesystems\n salt '*' status.diskusage / /tmp # usage for / and /tmp\n salt '*' status.diskusage ext? # usage for ext[234] filesystems\n salt '*' status.diskusage / ext? # usage for / and all ext filesystems\n '''\n selected = set()\n fstypes = set()\n if not args:\n # select all filesystems\n fstypes.add('*')\n else:\n for arg in args:\n if arg.startswith('/'):\n # select path\n selected.add(arg)\n else:\n # select fstype\n fstypes.add(arg)\n\n if fstypes:\n # determine which mount points host the specified fstypes\n regex = re.compile(\n '|'.join(\n fnmatch.translate(fstype).format('(%s)') for fstype in fstypes\n )\n )\n # ifile source of data varies with OS, otherwise all the same\n if __grains__['kernel'] == 'Linux':\n try:\n with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:\n ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()\n except OSError:\n return {}\n elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):\n ifile = __salt__['cmd.run']('mount -p').splitlines()\n else:\n raise CommandExecutionError('status.diskusage not yet supported on this platform')\n\n for line in ifile:\n comps = line.split()\n if __grains__['kernel'] == 'SunOS':\n if len(comps) >= 4:\n mntpt = comps[2]\n fstype = comps[3]\n if regex.match(fstype):\n selected.add(mntpt)\n else:\n if len(comps) >= 3:\n mntpt = comps[1]\n fstype = comps[2]\n if regex.match(fstype):\n selected.add(mntpt)\n\n # query the filesystems disk usage\n ret = {}\n for path in selected:\n fsstats = os.statvfs(path)\n blksz = fsstats.f_bsize\n available = fsstats.f_bavail * blksz\n total = fsstats.f_blocks * blksz\n ret[path] = {\"available\": available, \"total\": total}\n return ret\n",
"def uptime():\n '''\n Return the uptime for this system.\n\n .. versionchanged:: 2015.8.9\n The uptime function was changed to return a dictionary of easy-to-read\n key/value pairs containing uptime information, instead of the output\n from a ``cmd.run`` call.\n\n .. versionchanged:: 2016.11.0\n Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.uptime\n '''\n curr_seconds = time.time()\n\n # Get uptime in seconds\n if salt.utils.platform.is_linux():\n ut_path = \"/proc/uptime\"\n if not os.path.exists(ut_path):\n raise CommandExecutionError(\"File {ut_path} was not found.\".format(ut_path=ut_path))\n with salt.utils.files.fopen(ut_path) as rfh:\n seconds = int(float(rfh.read().split()[0]))\n elif salt.utils.platform.is_sunos():\n # note: some flavors/versions report the host uptime inside a zone\n # https://support.oracle.com/epmos/faces/BugDisplay?id=15611584\n res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')\n if res['retcode'] > 0:\n raise CommandExecutionError('The boot_time kstat was not found.')\n seconds = int(curr_seconds - int(res['stdout'].split()[-1]))\n elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():\n bt_data = __salt__['sysctl.get']('kern.boottime')\n if not bt_data:\n raise CommandExecutionError('Cannot find kern.boottime system parameter')\n seconds = int(curr_seconds - int(bt_data))\n elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():\n # format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016\n bt_data = __salt__['sysctl.get']('kern.boottime')\n if not bt_data:\n raise CommandExecutionError('Cannot find kern.boottime system parameter')\n data = bt_data.split(\"{\")[-1].split(\"}\")[0].strip().replace(' ', '')\n uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])\n seconds = int(curr_seconds - uptime['sec'])\n elif salt.utils.platform.is_aix():\n seconds = _get_boot_time_aix()\n else:\n return __salt__['cmd.run']('uptime')\n\n # Setup datetime and timedelta objects\n boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)\n curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)\n up_time = curr_time - boot_time\n\n # Construct return information\n ut_ret = {\n 'seconds': seconds,\n 'since_iso': boot_time.isoformat(),\n 'since_t': int(curr_seconds - seconds),\n 'days': up_time.days,\n 'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),\n }\n\n if salt.utils.path.which('who'):\n who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s\n ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))\n\n return ut_ret\n",
"def netdev():\n '''\n .. versionchanged:: 2016.3.2\n Return the network device stats for this minion\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.netdev\n '''\n def linux_netdev():\n '''\n linux specific implementation of netdev\n '''\n ret = {}\n try:\n with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:\n stats = salt.utils.stringutils.to_unicode(fp_.read())\n except IOError:\n pass\n else:\n for line in stats.splitlines():\n if not line:\n continue\n if line.find(':') < 0:\n continue\n comps = line.split()\n # Fix lines like eth0:9999..'\n comps[0] = line.split(':')[0].strip()\n # Support lines both like eth0:999 and eth0: 9999\n comps.insert(1, line.split(':')[1].strip().split()[0])\n ret[comps[0]] = {'iface': comps[0],\n 'rx_bytes': _number(comps[2]),\n 'rx_compressed': _number(comps[8]),\n 'rx_drop': _number(comps[5]),\n 'rx_errs': _number(comps[4]),\n 'rx_fifo': _number(comps[6]),\n 'rx_frame': _number(comps[7]),\n 'rx_multicast': _number(comps[9]),\n 'rx_packets': _number(comps[3]),\n 'tx_bytes': _number(comps[10]),\n 'tx_carrier': _number(comps[16]),\n 'tx_colls': _number(comps[15]),\n 'tx_compressed': _number(comps[17]),\n 'tx_drop': _number(comps[13]),\n 'tx_errs': _number(comps[12]),\n 'tx_fifo': _number(comps[14]),\n 'tx_packets': _number(comps[11])}\n return ret\n\n def freebsd_netdev():\n '''\n freebsd specific implementation of netdev\n '''\n _dict_tree = lambda: collections.defaultdict(_dict_tree)\n ret = _dict_tree()\n netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()\n netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]\n header = netstat[0].split()\n for line in netstat[1:]:\n comps = line.split()\n for i in range(4, 13): # The columns we want\n ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])\n return ret\n\n def sunos_netdev():\n '''\n sunos specific implementation of netdev\n '''\n ret = {}\n ##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6\n for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:\n # fetch device info\n netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()\n netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()\n\n # prepare data\n netstat_ipv4[0] = netstat_ipv4[0].split()\n netstat_ipv4[1] = netstat_ipv4[1].split()\n netstat_ipv6[0] = netstat_ipv6[0].split()\n netstat_ipv6[1] = netstat_ipv6[1].split()\n\n # add data\n ret[dev] = {}\n for i in range(len(netstat_ipv4[0])-1):\n if netstat_ipv4[0][i] == 'Name':\n continue\n if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:\n ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]\n else:\n ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])\n for i in range(len(netstat_ipv6[0])-1):\n if netstat_ipv6[0][i] == 'Name':\n continue\n if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:\n ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]\n else:\n ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])\n\n return ret\n\n def aix_netdev():\n '''\n AIX specific implementation of netdev\n '''\n ret = {}\n fields = []\n procn = None\n for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():\n # fetch device info\n #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6\n #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll\n #en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0\n #en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0\n #root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6\n #Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll\n #en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0\n\n netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()\n netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()\n\n # add data\n ret[dev] = []\n\n for line in netstat_ipv4:\n if line.startswith('Name'):\n fields = line.split()\n continue\n\n comps = line.split()\n if len(comps) < 3:\n raise CommandExecutionError('Insufficent data returned by command to process \\'{0}\\''.format(line))\n\n if comps[2].startswith('link'):\n continue\n\n procn = len(ret[dev])\n ret[dev].append({})\n ret[dev][procn]['ipv4'] = {}\n for i in range(1, len(fields)):\n if len(comps) > i:\n ret[dev][procn]['ipv4'][fields[i]] = comps[i]\n\n for line in netstat_ipv6:\n if line.startswith('Name'):\n fields = line.split()\n continue\n\n comps = line.split()\n if len(comps) < 3:\n raise CommandExecutionError('Insufficent data returned by command to process \\'{0}\\''.format(line))\n\n if comps[2].startswith('link'):\n continue\n\n procn = len(ret[dev])\n ret[dev].append({})\n ret[dev][procn]['ipv6'] = {}\n for i in range(1, len(fields)):\n if len(comps) > i:\n ret[dev][procn]['ipv6'][fields[i]] = comps[i]\n\n return ret\n\n # dict that returns a function that does the right thing per platform\n get_version = {\n 'Linux': linux_netdev,\n 'FreeBSD': freebsd_netdev,\n 'SunOS': sunos_netdev,\n 'AIX': aix_netdev,\n }\n\n errmsg = 'This method is unsupported on the current operating system!'\n return get_version.get(__grains__['kernel'], lambda: errmsg)()\n",
"def cpustats():\n '''\n Return the CPU stats for this minion\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n .. versionchanged:: 2018.3.0\n Added support for OpenBSD\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.cpustats\n '''\n def linux_cpustats():\n '''\n linux specific implementation of cpustats\n '''\n ret = {}\n try:\n with salt.utils.files.fopen('/proc/stat', 'r') as fp_:\n stats = salt.utils.stringutils.to_unicode(fp_.read())\n except IOError:\n pass\n else:\n for line in stats.splitlines():\n if not line:\n continue\n comps = line.split()\n if comps[0] == 'cpu':\n ret[comps[0]] = {'idle': _number(comps[4]),\n 'iowait': _number(comps[5]),\n 'irq': _number(comps[6]),\n 'nice': _number(comps[2]),\n 'softirq': _number(comps[7]),\n 'steal': _number(comps[8]),\n 'system': _number(comps[3]),\n 'user': _number(comps[1])}\n elif comps[0] == 'intr':\n ret[comps[0]] = {'total': _number(comps[1]),\n 'irqs': [_number(x) for x in comps[2:]]}\n elif comps[0] == 'softirq':\n ret[comps[0]] = {'total': _number(comps[1]),\n 'softirqs': [_number(x) for x in comps[2:]]}\n else:\n ret[comps[0]] = _number(comps[1])\n return ret\n\n def freebsd_cpustats():\n '''\n freebsd specific implementation of cpustats\n '''\n vmstat = __salt__['cmd.run']('vmstat -P').splitlines()\n vm0 = vmstat[0].split()\n cpu0loc = vm0.index('cpu0')\n vm1 = vmstat[1].split()\n usloc = vm1.index('us')\n vm2 = vmstat[2].split()\n cpuctr = 0\n ret = {}\n for cpu in vm0[cpu0loc:]:\n ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),\n 'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),\n 'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }\n cpuctr += 1\n return ret\n\n def sunos_cpustats():\n '''\n sunos specific implementation of cpustats\n '''\n mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()\n fields = mpstat[0].split()\n ret = {}\n for cpu in mpstat:\n if cpu.startswith('CPU'):\n continue\n cpu = cpu.split()\n ret[_number(cpu[0])] = {}\n for i in range(1, len(fields)-1):\n ret[_number(cpu[0])][fields[i]] = _number(cpu[i])\n return ret\n\n def aix_cpustats():\n '''\n AIX specific implementation of cpustats\n '''\n ret = {}\n ret['mpstat'] = []\n procn = None\n fields = []\n for line in __salt__['cmd.run']('mpstat -a').splitlines():\n if not line:\n continue\n procn = len(ret['mpstat'])\n if line.startswith('System'):\n comps = line.split(':')\n ret['mpstat'].append({})\n ret['mpstat'][procn]['system'] = {}\n cpu_comps = comps[1].split()\n for i in range(0, len(cpu_comps)):\n cpu_vals = cpu_comps[i].split('=')\n ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]\n\n if line.startswith('cpu'):\n fields = line.split()\n continue\n\n if fields:\n cpustat = line.split()\n ret[_number(cpustat[0])] = {}\n for i in range(1, len(fields)-1):\n ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])\n\n return ret\n\n def openbsd_cpustats():\n '''\n openbsd specific implementation of cpustats\n '''\n systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()\n fields = systat[3].split()\n ret = {}\n for cpu in systat[4:]:\n cpu_line = cpu.split()\n cpu_idx = cpu_line[0]\n ret[cpu_idx] = {}\n\n for idx, field in enumerate(fields[1:]):\n ret[cpu_idx][field] = cpu_line[idx+1]\n\n return ret\n\n # dict that return a function that does the right thing per platform\n get_version = {\n 'Linux': linux_cpustats,\n 'FreeBSD': freebsd_cpustats,\n 'OpenBSD': openbsd_cpustats,\n 'SunOS': sunos_cpustats,\n 'AIX': aix_cpustats,\n }\n\n errmsg = 'This method is unsupported on the current operating system!'\n return get_version.get(__grains__['kernel'], lambda: errmsg)()\n",
"def vmstats():\n '''\n .. versionchanged:: 2016.3.2\n Return the virtual memory stats for this minion\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.vmstats\n '''\n def linux_vmstats():\n '''\n linux specific implementation of vmstats\n '''\n ret = {}\n try:\n with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:\n stats = salt.utils.stringutils.to_unicode(fp_.read())\n except IOError:\n pass\n else:\n for line in stats.splitlines():\n if not line:\n continue\n comps = line.split()\n ret[comps[0]] = _number(comps[1])\n return ret\n\n def generic_vmstats():\n '''\n generic implementation of vmstats\n note: works on FreeBSD, SunOS and OpenBSD (possibly others)\n '''\n ret = {}\n for line in __salt__['cmd.run']('vmstat -s').splitlines():\n comps = line.split()\n if comps[0].isdigit():\n ret[' '.join(comps[1:])] = _number(comps[0].strip())\n return ret\n\n # dict that returns a function that does the right thing per platform\n get_version = {\n 'Linux': linux_vmstats,\n 'FreeBSD': generic_vmstats,\n 'OpenBSD': generic_vmstats,\n 'SunOS': generic_vmstats,\n 'AIX': generic_vmstats,\n }\n\n errmsg = 'This method is unsupported on the current operating system!'\n return get_version.get(__grains__['kernel'], lambda: errmsg)()\n",
"def diskstats():\n '''\n .. versionchanged:: 2016.3.2\n Return the disk stats for this minion\n\n .. versionchanged:: 2016.11.4\n Added support for AIX\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' status.diskstats\n '''\n def linux_diskstats():\n '''\n linux specific implementation of diskstats\n '''\n ret = {}\n try:\n with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:\n stats = salt.utils.stringutils.to_unicode(fp_.read())\n except IOError:\n pass\n else:\n for line in stats.splitlines():\n if not line:\n continue\n comps = line.split()\n ret[comps[2]] = {\n 'major': _number(comps[0]),\n 'minor': _number(comps[1]),\n 'device': _number(comps[2]),\n 'reads_issued': _number(comps[3]),\n 'reads_merged': _number(comps[4]),\n 'sectors_read': _number(comps[5]),\n 'ms_spent_reading': _number(comps[6]),\n 'writes_completed': _number(comps[7]),\n 'writes_merged': _number(comps[8]),\n 'sectors_written': _number(comps[9]),\n 'ms_spent_writing': _number(comps[10]),\n 'io_in_progress': _number(comps[11]),\n 'ms_spent_in_io': _number(comps[12]),\n 'weighted_ms_spent_in_io': _number(comps[13])\n }\n return ret\n\n def generic_diskstats():\n '''\n generic implementation of diskstats\n note: freebsd and sunos\n '''\n ret = {}\n iostat = __salt__['cmd.run']('iostat -xzd').splitlines()\n header = iostat[1]\n for line in iostat[2:]:\n comps = line.split()\n ret[comps[0]] = {}\n for metric, value in zip(header.split()[1:], comps[1:]):\n ret[comps[0]][metric] = _number(value)\n return ret\n\n def aix_diskstats():\n '''\n AIX specific implementation of diskstats\n '''\n ret = {}\n procn = None\n fields = []\n disk_name = ''\n disk_mode = ''\n for line in __salt__['cmd.run']('iostat -dDV').splitlines():\n # Note: iostat -dDV is per-system\n #\n #System configuration: lcpu=8 drives=1 paths=2 vdisks=2\n #\n #hdisk0 xfer: %tm_act bps tps bread bwrtn\n # 0.0 0.8 0.0 0.0 0.8\n # read: rps avgserv minserv maxserv timeouts fails\n # 0.0 2.5 0.3 12.4 0 0\n # write: wps avgserv minserv maxserv timeouts fails\n # 0.0 0.3 0.2 0.7 0 0\n # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull\n # 0.3 0.0 5.3 0.0 0.0 0.0\n #--------------------------------------------------------------------------------\n if not line or line.startswith('System') or line.startswith('-----------'):\n continue\n\n if not re.match(r'\\s', line):\n #have new disk\n dsk_comps = line.split(':')\n dsk_firsts = dsk_comps[0].split()\n disk_name = dsk_firsts[0]\n disk_mode = dsk_firsts[1]\n fields = dsk_comps[1].split()\n ret[disk_name] = []\n\n procn = len(ret[disk_name])\n ret[disk_name].append({})\n ret[disk_name][procn][disk_mode] = {}\n continue\n\n if ':' in line:\n comps = line.split(':')\n fields = comps[1].split()\n disk_mode = comps[0].lstrip()\n procn = len(ret[disk_name])\n ret[disk_name].append({})\n ret[disk_name][procn][disk_mode] = {}\n else:\n comps = line.split()\n for i in range(0, len(fields)):\n if len(comps) > i:\n ret[disk_name][procn][disk_mode][fields[i]] = comps[i]\n\n return ret\n\n # dict that return a function that does the right thing per platform\n get_version = {\n 'Linux': linux_diskstats,\n 'FreeBSD': generic_diskstats,\n 'SunOS': generic_diskstats,\n 'AIX': aix_diskstats,\n }\n\n errmsg = 'This method is unsupported on the current operating system!'\n return get_version.get(__grains__['kernel'], lambda: errmsg)()\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import logging
import fnmatch
import collections
import copy
import time
import logging
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.config
import salt.minion
import salt.utils.event
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__file__)
__virtualname__ = 'status'
__opts__ = {}
# Don't shadow built-in's.
__func_alias__ = {
'time_': 'time'
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Not all functions supported by Windows
'''
if salt.utils.platform.is_windows():
return False, 'Windows platform is not supported by this module'
return __virtualname__
def _number(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
if text.isdigit():
return int(text)
try:
return float(text)
except ValueError:
return text
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
'''
boot_secs = 0
res = __salt__['cmd.run_all']('ps -o etime= -p 1')
if res['retcode'] > 0:
raise CommandExecutionError('Unable to find boot_time for pid 1.')
bt_time = res['stdout']
days = bt_time.split('-')
hms = days[1].split(':')
boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2])
return boot_secs
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
'5-min': load_avg[2].strip(','),
'15-min': load_avg[3]}
def _aix_nproc():
'''
Return the maximun number of PROCESSES allowed per user on AIX
'''
nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split()
return _number(nprocs[1])
def procs():
'''
Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs
'''
# Get the user, pid and cmd
ret = {}
uind = 0
pind = 0
cind = 0
plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines()
guide = plines.pop(0).split()
if 'USER' in guide:
uind = guide.index('USER')
elif 'UID' in guide:
uind = guide.index('UID')
if 'PID' in guide:
pind = guide.index('PID')
if 'COMMAND' in guide:
cind = guide.index('COMMAND')
elif 'CMD' in guide:
cind = guide.index('CMD')
for line in plines:
if not line:
continue
comps = line.split()
ret[comps[pind]] = {'user': comps[uind],
'cmd': ' '.join(comps[cind:])}
return ret
def custom():
'''
Return a custom composite of status data and info for this minion,
based on the minion config file. An example config like might be::
status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ]
Where status refers to status.py, cpustats is the function
where we get our data, and custom is this function It is followed
by a list of keys that we want returned.
This function is meant to replace all_status(), which returns
anything and everything, which we probably don't want.
By default, nothing is returned. Warning: Depending on what you
include, there can be a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.custom
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
for key, val in six.iteritems(conf):
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123
for item in val:
ret[item] = vals[item]
return ret
def uptime():
'''
Return the uptime for this system.
.. versionchanged:: 2015.8.9
The uptime function was changed to return a dictionary of easy-to-read
key/value pairs containing uptime information, instead of the output
from a ``cmd.run`` call.
.. versionchanged:: 2016.11.0
Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.uptime
'''
curr_seconds = time.time()
# Get uptime in seconds
if salt.utils.platform.is_linux():
ut_path = "/proc/uptime"
if not os.path.exists(ut_path):
raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path))
with salt.utils.files.fopen(ut_path) as rfh:
seconds = int(float(rfh.read().split()[0]))
elif salt.utils.platform.is_sunos():
# note: some flavors/versions report the host uptime inside a zone
# https://support.oracle.com/epmos/faces/BugDisplay?id=15611584
res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')
if res['retcode'] > 0:
raise CommandExecutionError('The boot_time kstat was not found.')
seconds = int(curr_seconds - int(res['stdout'].split()[-1]))
elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
seconds = int(curr_seconds - int(bt_data))
elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():
# format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '')
uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])
seconds = int(curr_seconds - uptime['sec'])
elif salt.utils.platform.is_aix():
seconds = _get_boot_time_aix()
else:
return __salt__['cmd.run']('uptime')
# Setup datetime and timedelta objects
boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)
curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)
up_time = curr_time - boot_time
# Construct return information
ut_ret = {
'seconds': seconds,
'since_iso': boot_time.isoformat(),
'since_t': int(curr_seconds - seconds),
'days': up_time.days,
'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),
}
if salt.utils.path.which('who'):
who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s
ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))
return ut_ret
def loadavg():
'''
Return the load averages for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.loadavg
:raises CommandExecutionError: If the system cannot report loadaverages to Python
'''
if __grains__['kernel'] == 'AIX':
return _aix_loadavg()
try:
load_avg = os.getloadavg()
except AttributeError:
# Some UNIX-based operating systems do not have os.getloadavg()
raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')
return {'1-min': load_avg[0],
'5-min': load_avg[1],
'15-min': load_avg[2]}
def cpustats():
'''
Return the CPU stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpustats
'''
def linux_cpustats():
'''
linux specific implementation of cpustats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == 'cpu':
ret[comps[0]] = {'idle': _number(comps[4]),
'iowait': _number(comps[5]),
'irq': _number(comps[6]),
'nice': _number(comps[2]),
'softirq': _number(comps[7]),
'steal': _number(comps[8]),
'system': _number(comps[3]),
'user': _number(comps[1])}
elif comps[0] == 'intr':
ret[comps[0]] = {'total': _number(comps[1]),
'irqs': [_number(x) for x in comps[2:]]}
elif comps[0] == 'softirq':
ret[comps[0]] = {'total': _number(comps[1]),
'softirqs': [_number(x) for x in comps[2:]]}
else:
ret[comps[0]] = _number(comps[1])
return ret
def freebsd_cpustats():
'''
freebsd specific implementation of cpustats
'''
vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
vm0 = vmstat[0].split()
cpu0loc = vm0.index('cpu0')
vm1 = vmstat[1].split()
usloc = vm1.index('us')
vm2 = vmstat[2].split()
cpuctr = 0
ret = {}
for cpu in vm0[cpu0loc:]:
ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
cpuctr += 1
return ret
def sunos_cpustats():
'''
sunos specific implementation of cpustats
'''
mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
fields = mpstat[0].split()
ret = {}
for cpu in mpstat:
if cpu.startswith('CPU'):
continue
cpu = cpu.split()
ret[_number(cpu[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
return ret
def aix_cpustats():
'''
AIX specific implementation of cpustats
'''
ret = {}
ret['mpstat'] = []
procn = None
fields = []
for line in __salt__['cmd.run']('mpstat -a').splitlines():
if not line:
continue
procn = len(ret['mpstat'])
if line.startswith('System'):
comps = line.split(':')
ret['mpstat'].append({})
ret['mpstat'][procn]['system'] = {}
cpu_comps = comps[1].split()
for i in range(0, len(cpu_comps)):
cpu_vals = cpu_comps[i].split('=')
ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]
if line.startswith('cpu'):
fields = line.split()
continue
if fields:
cpustat = line.split()
ret[_number(cpustat[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])
return ret
def openbsd_cpustats():
'''
openbsd specific implementation of cpustats
'''
systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
fields = systat[3].split()
ret = {}
for cpu in systat[4:]:
cpu_line = cpu.split()
cpu_idx = cpu_line[0]
ret[cpu_idx] = {}
for idx, field in enumerate(fields[1:]):
ret[cpu_idx][field] = cpu_line[idx+1]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_cpustats,
'FreeBSD': freebsd_cpustats,
'OpenBSD': openbsd_cpustats,
'SunOS': sunos_cpustats,
'AIX': aix_cpustats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''
linux specific implementation of meminfo
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {
'value': comps[1],
}
if len(comps) > 2:
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'''
freebsd specific implementation of meminfo
'''
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
# Special handling for vm.total as it's especially important
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
def aix_meminfo():
'''
AIX specific implementation of meminfo
'''
ret = {}
ret['svmon'] = []
ret['vmstat'] = []
procn = None
fields = []
pagesize_flag = False
for line in __salt__['cmd.run']('svmon -G').splitlines():
# Note: svmon is per-system
# size inuse free pin virtual mmode
#memory 1048576 1039740 8836 285078 474993 Ded
#pg space 917504 2574
#
# work pers clnt other
#pin 248379 0 2107 34592
#in use 474993 0 564747
#
#PageSize PoolSize inuse pgsp pin virtual
#s 4 KB - 666956 2574 60726 102209
#m 64 KB - 23299 0 14022 23299
if not line:
continue
if re.match(r'\s', line):
# assume fields line
fields = line.split()
continue
if line.startswith('memory') or line.startswith('pin'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i + 1:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
continue
if line.startswith('pg space') or line.startswith('in use'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
pg_space = '{0} {1}'.format(comps[0], comps[1])
ret['svmon'][procn][pg_space] = {}
for i in range(0, len(fields)):
if len(comps) > i + 2:
ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
continue
if line.startswith('PageSize'):
fields = line.split()
pagesize_flag = False
continue
if pagesize_flag:
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
continue
for line in __salt__['cmd.run']('vmstat -v').splitlines():
# Note: vmstat is per-system
if not line:
continue
procn = len(ret['vmstat'])
ret['vmstat'].append({})
comps = line.lstrip().split(' ', 1)
ret['vmstat'][procn][comps[1]] = comps[0]
return ret
def openbsd_meminfo():
'''
openbsd specific implementation of meminfo
'''
vmstat = __salt__['cmd.run']('vmstat').splitlines()
# We're only interested in memory and page values which are printed
# as subsequent fields.
fields = ['active virtual pages', 'free list size', 'page faults',
'pages reclaimed', 'pages paged in', 'pages paged out',
'pages freed', 'pages scanned']
data = vmstat[2].split()[2:10]
ret = dict(zip(fields, data))
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_meminfo,
'FreeBSD': freebsd_meminfo,
'OpenBSD': openbsd_meminfo,
'AIX': aix_meminfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def cpuinfo():
'''
.. versionchanged:: 2016.3.2
Return the CPU info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for NetBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpuinfo
'''
def linux_cpuinfo():
'''
linux specific cpuinfo implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
if comps[0] == 'flags':
ret[comps[0]] = comps[1].split()
else:
ret[comps[0]] = comps[1].strip()
return ret
def bsd_cpuinfo():
'''
bsd specific cpuinfo implementation
'''
bsd_cmd = 'sysctl hw.model hw.ncpu'
ret = {}
if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:
sep = '='
else:
sep = ':'
for line in __salt__['cmd.run'](bsd_cmd).splitlines():
if not line:
continue
comps = line.split(sep)
comps[0] = comps[0].strip()
ret[comps[0]] = comps[1].strip()
return ret
def sunos_cpuinfo():
'''
sunos specific cpuinfo implementation
'''
ret = {}
ret['isainfo'] = {}
for line in __salt__['cmd.run']('isainfo -x').splitlines():
# Note: isainfo is per-system and not per-cpu
# Output Example:
#amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu
#i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())
ret['psrinfo'] = []
procn = None
for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():
# Output Example:
#The physical processor has 6 cores and 12 virtual processors (0-5 12-17)
# The core has 2 virtual processors (0 12)
# The core has 2 virtual processors (1 13)
# The core has 2 virtual processors (2 14)
# The core has 2 virtual processors (3 15)
# The core has 2 virtual processors (4 16)
# The core has 2 virtual processors (5 17)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#The physical processor has 6 cores and 12 virtual processors (6-11 18-23)
# The core has 2 virtual processors (6 18)
# The core has 2 virtual processors (7 19)
# The core has 2 virtual processors (8 20)
# The core has 2 virtual processors (9 21)
# The core has 2 virtual processors (10 22)
# The core has 2 virtual processors (11 23)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#
# Output Example 2:
#The physical processor has 4 virtual processors (0-3)
# x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)
# Intel(r) Atom(tm) CPU C2558 @ 2.40GHz
if not line:
continue
if line.startswith('The physical processor'):
procn = len(ret['psrinfo'])
line = line.split()
ret['psrinfo'].append({})
if 'cores' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])
ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])
elif 'virtual' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])
elif line.startswith(' ' * 6): # 3x2 space indent
ret['psrinfo'][procn]['name'] = line.strip()
elif line.startswith(' ' * 4): # 2x2 space indent
line = line.strip().split()
ret['psrinfo'][procn]['vendor'] = line[1][1:]
ret['psrinfo'][procn]['family'] = _number(line[4])
ret['psrinfo'][procn]['model'] = _number(line[6])
ret['psrinfo'][procn]['step'] = _number(line[8])
ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1])
return ret
def aix_cpuinfo():
'''
AIX specific cpuinfo implementation
'''
ret = {}
ret['prtconf'] = []
ret['lparstat'] = []
procn = None
for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#prtconf | grep -i "Processor"
#Processor Type: PowerPC_POWER7
#Processor Implementation Mode: POWER 7
#Processor Version: PV_7_Compat
#Number Of Processors: 2
#Processor Clock Speed: 3000 MHz
# Model Implementation: Multiple Processor, PCI bus
# + proc0 Processor
# + proc4 Processor
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('Processor') or line.startswith('Number'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#CPU Type: 64-bit
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('CPU'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():
# Note: lparstat is per-system and not per-cpu
# Output Example:
#Online Virtual CPUs : 2
#Maximum Virtual CPUs : 2
#Minimum Virtual CPUs : 1
#Maximum Physical CPUs in system : 32
#Active Physical CPUs in system : 32
#Active CPUs in Pool : 32
#Shared Physical CPUs in system : 32
#Physical CPU Percentage : 25.00%
#Desired Virtual CPUs : 2
if not line:
continue
procn = len(ret['lparstat'])
ret['lparstat'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['lparstat'][procn][comps[0]] = comps[1]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_cpuinfo,
'FreeBSD': bsd_cpuinfo,
'NetBSD': bsd_cpuinfo,
'OpenBSD': bsd_cpuinfo,
'SunOS': sunos_cpuinfo,
'AIX': aix_cpuinfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific implementation of diskstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[2]] = {
'major': _number(comps[0]),
'minor': _number(comps[1]),
'device': _number(comps[2]),
'reads_issued': _number(comps[3]),
'reads_merged': _number(comps[4]),
'sectors_read': _number(comps[5]),
'ms_spent_reading': _number(comps[6]),
'writes_completed': _number(comps[7]),
'writes_merged': _number(comps[8]),
'sectors_written': _number(comps[9]),
'ms_spent_writing': _number(comps[10]),
'io_in_progress': _number(comps[11]),
'ms_spent_in_io': _number(comps[12]),
'weighted_ms_spent_in_io': _number(comps[13])
}
return ret
def generic_diskstats():
'''
generic implementation of diskstats
note: freebsd and sunos
'''
ret = {}
iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
header = iostat[1]
for line in iostat[2:]:
comps = line.split()
ret[comps[0]] = {}
for metric, value in zip(header.split()[1:], comps[1:]):
ret[comps[0]][metric] = _number(value)
return ret
def aix_diskstats():
'''
AIX specific implementation of diskstats
'''
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
for line in __salt__['cmd.run']('iostat -dDV').splitlines():
# Note: iostat -dDV is per-system
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk0 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.8 0.0 0.0 0.8
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 2.5 0.3 12.4 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.3 0.2 0.7 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.3 0.0 5.3 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#have new disk
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()
ret[disk_name] = []
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
else:
comps = line.split()
for i in range(0, len(fields)):
if len(comps) > i:
ret[disk_name][procn][disk_mode][fields[i]] = comps[i]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_diskstats,
'FreeBSD': generic_diskstats,
'SunOS': generic_diskstats,
'AIX': aix_diskstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskusage(*args):
'''
Return the disk usage for this minion
Usage::
salt '*' status.diskusage [paths and/or filesystem types]
CLI Example:
.. code-block:: bash
salt '*' status.diskusage # usage for all filesystems
salt '*' status.diskusage / /tmp # usage for / and /tmp
salt '*' status.diskusage ext? # usage for ext[234] filesystems
salt '*' status.diskusage / ext? # usage for / and all ext filesystems
'''
selected = set()
fstypes = set()
if not args:
# select all filesystems
fstypes.add('*')
else:
for arg in args:
if arg.startswith('/'):
# select path
selected.add(arg)
else:
# select fstype
fstypes.add(arg)
if fstypes:
# determine which mount points host the specified fstypes
regex = re.compile(
'|'.join(
fnmatch.translate(fstype).format('(%s)') for fstype in fstypes
)
)
# ifile source of data varies with OS, otherwise all the same
if __grains__['kernel'] == 'Linux':
try:
with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:
ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()
except OSError:
return {}
elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):
ifile = __salt__['cmd.run']('mount -p').splitlines()
else:
raise CommandExecutionError('status.diskusage not yet supported on this platform')
for line in ifile:
comps = line.split()
if __grains__['kernel'] == 'SunOS':
if len(comps) >= 4:
mntpt = comps[2]
fstype = comps[3]
if regex.match(fstype):
selected.add(mntpt)
else:
if len(comps) >= 3:
mntpt = comps[1]
fstype = comps[2]
if regex.match(fstype):
selected.add(mntpt)
# query the filesystems disk usage
ret = {}
for path in selected:
fsstats = os.statvfs(path)
blksz = fsstats.f_bsize
available = fsstats.f_bavail * blksz
total = fsstats.f_blocks * blksz
ret[path] = {"available": available, "total": total}
return ret
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specific implementation of vmstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[0]] = _number(comps[1])
return ret
def generic_vmstats():
'''
generic implementation of vmstats
note: works on FreeBSD, SunOS and OpenBSD (possibly others)
'''
ret = {}
for line in __salt__['cmd.run']('vmstat -s').splitlines():
comps = line.split()
if comps[0].isdigit():
ret[' '.join(comps[1:])] = _number(comps[0].strip())
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_vmstats,
'FreeBSD': generic_vmstats,
'OpenBSD': generic_vmstats,
'SunOS': generic_vmstats,
'AIX': generic_vmstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def nproc():
'''
Return the number of processing units available on this system
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for Darwin, FreeBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.nproc
'''
def linux_nproc():
'''
linux specific implementation of nproc
'''
try:
return _number(__salt__['cmd.run']('nproc').strip())
except ValueError:
return 0
def generic_nproc():
'''
generic implementation of nproc
'''
ncpu_data = __salt__['sysctl.get']('hw.ncpu')
if not ncpu_data:
# We need at least one CPU to run
return 1
else:
return _number(ncpu_data)
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_nproc,
'Darwin': generic_nproc,
'FreeBSD': generic_nproc,
'OpenBSD': generic_nproc,
'AIX': _aix_nproc,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netstats():
'''
Return the network stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.netstats
'''
def linux_netstats():
'''
linux specific netstats implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
headers = ['']
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
else:
headers = comps
return ret
def freebsd_netstats():
return bsd_netstats()
def bsd_netstats():
'''
bsd specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
if line.startswith('\t\t'):
continue # Skip, too detailed
if not line.startswith('\t'):
key = line.split()[0].replace(':', '')
ret[key] = {}
else:
comps = line.split()
if comps[0].isdigit():
ret[key][' '.join(comps[1:])] = comps[0]
return ret
def sunos_netstats():
'''
sunos specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
line = line.replace('=', ' = ').split()
if len(line) > 6:
line.pop(0)
if '=' in line:
if len(line) >= 3:
if line[2].isdigit() or line[2][0] == '-':
line[2] = _number(line[2])
ret[line[0]] = line[2]
if len(line) >= 6:
if line[5].isdigit() or line[5][0] == '-':
line[5] = _number(line[5])
ret[line[3]] = line[5]
return ret
def aix_netstats():
'''
AIX specific netstats implementation
'''
ret = {}
fields = []
procn = None
proto_name = None
for line in __salt__['cmd.run']('netstat -s').splitlines():
if not line:
continue
if not re.match(r'\s', line) and ':' in line:
comps = line.split(':')
proto_name = comps[0]
ret[proto_name] = []
procn = len(ret[proto_name])
ret[proto_name].append({})
continue
else:
comps = line.split()
comps[0] = comps[0].strip()
if comps[0].isdigit():
ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])
else:
continue
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netstats,
'FreeBSD': bsd_netstats,
'OpenBSD': bsd_netstats,
'SunOS': sunos_netstats,
'AIX': aix_netstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific implementation of netdev
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
if line.find(':') < 0:
continue
comps = line.split()
# Fix lines like eth0:9999..'
comps[0] = line.split(':')[0].strip()
# Support lines both like eth0:999 and eth0: 9999
comps.insert(1, line.split(':')[1].strip().split()[0])
ret[comps[0]] = {'iface': comps[0],
'rx_bytes': _number(comps[2]),
'rx_compressed': _number(comps[8]),
'rx_drop': _number(comps[5]),
'rx_errs': _number(comps[4]),
'rx_fifo': _number(comps[6]),
'rx_frame': _number(comps[7]),
'rx_multicast': _number(comps[9]),
'rx_packets': _number(comps[3]),
'tx_bytes': _number(comps[10]),
'tx_carrier': _number(comps[16]),
'tx_colls': _number(comps[15]),
'tx_compressed': _number(comps[17]),
'tx_drop': _number(comps[13]),
'tx_errs': _number(comps[12]),
'tx_fifo': _number(comps[14]),
'tx_packets': _number(comps[11])}
return ret
def freebsd_netdev():
'''
freebsd specific implementation of netdev
'''
_dict_tree = lambda: collections.defaultdict(_dict_tree)
ret = _dict_tree()
netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()
netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]
header = netstat[0].split()
for line in netstat[1:]:
comps = line.split()
for i in range(4, 13): # The columns we want
ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])
return ret
def sunos_netdev():
'''
sunos specific implementation of netdev
'''
ret = {}
##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:
# fetch device info
netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()
# prepare data
netstat_ipv4[0] = netstat_ipv4[0].split()
netstat_ipv4[1] = netstat_ipv4[1].split()
netstat_ipv6[0] = netstat_ipv6[0].split()
netstat_ipv6[1] = netstat_ipv6[1].split()
# add data
ret[dev] = {}
for i in range(len(netstat_ipv4[0])-1):
if netstat_ipv4[0][i] == 'Name':
continue
if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]
else:
ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])
for i in range(len(netstat_ipv6[0])-1):
if netstat_ipv6[0][i] == 'Name':
continue
if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]
else:
ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])
return ret
def aix_netdev():
'''
AIX specific implementation of netdev
'''
ret = {}
fields = []
procn = None
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():
# fetch device info
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0
#en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0
netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()
# add data
ret[dev] = []
for line in netstat_ipv4:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv4'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv4'][fields[i]] = comps[i]
for line in netstat_ipv6:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv6'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv6'][fields[i]] = comps[i]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netdev,
'FreeBSD': freebsd_netdev,
'SunOS': sunos_netdev,
'AIX': aix_netdev,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def w(): # pylint: disable=C0103
'''
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
'''
def linux_w():
'''
Linux specific implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -fh').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'idle': comps[3],
'jcpu': comps[4],
'login': comps[2],
'pcpu': comps[5],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[6:])}
user_list.append(rec)
return user_list
def bsd_w():
'''
Generic BSD implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -h').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'from': comps[2],
'idle': comps[4],
'login': comps[3],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[5:])}
user_list.append(rec)
return user_list
# dict that returns a function that does the right thing per platform
get_version = {
'Darwin': bsd_w,
'FreeBSD': bsd_w,
'Linux': linux_w,
'OpenBSD': bsd_w,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
'''
cmd = __grains__['ps']
output = __salt__['cmd.run_stdout'](cmd, python_shell=True)
pids = ''
for line in output.splitlines():
if 'status.pid' in line:
continue
if re.search(sig, line):
if pids:
pids += '\n'
pids += line.split()[1]
return pids
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
'''
linux specific implementation of version
'''
try:
with salt.utils.files.fopen('/proc/version', 'r') as fp_:
return salt.utils.stringutils.to_unicode(fp_.read()).strip()
except IOError:
return {}
def bsd_version():
'''
bsd specific implementation of version
'''
return __salt__['cmd.run']('sysctl -n kern.version')
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_version,
'FreeBSD': bsd_version,
'OpenBSD': bsd_version,
'AIX': lambda: __salt__['cmd.run']('oslevel -s'),
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def master(master=None, connected=True):
'''
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
master_ips = None
if master:
master_ips = salt.utils.network.host_to_ips(master)
if not master_ips:
return
master_connection_status = False
port = __salt__['config.get']('publish_port', default=4505)
connected_ips = salt.utils.network.remote_port_tcp(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
def ping_master(master):
'''
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
'''
if master is None or master == '':
return False
opts = copy.deepcopy(__opts__)
opts['master'] = master
if 'master_ip' in opts: # avoid 'master ip changed' warning
del opts['master_ip']
opts.update(salt.minion.prep_ip_port(opts))
try:
opts.update(salt.minion.resolve_dns(opts, fallback=False))
except Exception:
return False
timeout = opts.get('auth_timeout', 60)
load = {'cmd': 'ping'}
result = False
channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear')
try:
payload = channel.send(load, tries=0, timeout=timeout)
result = True
except Exception as e:
pass
if result:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
event.fire_event({'master': master}, salt.minion.master_event(type='failback'))
return result
def proxy_reconnect(proxy_name, opts=None):
'''
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
'''
if not opts:
opts = __opts__
if 'proxy' not in opts:
return False # fail
proxy_keepalive_fn = proxy_name+'.alive'
if proxy_keepalive_fn not in __proxy__:
return False # fail
is_alive = __proxy__[proxy_keepalive_fn](opts)
if not is_alive:
minion_id = opts.get('proxyid', '') or opts.get('id', '')
log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name)
__proxy__[proxy_name+'.shutdown'](opts) # safely close connection
__proxy__[proxy_name+'.init'](opts) # reopen connection
log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name)
return True # success
def time_(format='%A, %d. %B %Y %I:%M%p'):
'''
.. versionadded:: 2016.3.0
Return the current time on the minion,
formatted based on the format parameter.
Default date format: Monday, 27. July 2015 07:55AM
CLI Example:
.. code-block:: bash
salt '*' status.time
salt '*' status.time '%s'
'''
dt = datetime.datetime.today()
return dt.strftime(format)
|
saltstack/salt
|
salt/modules/status.py
|
pid
|
python
|
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
'''
cmd = __grains__['ps']
output = __salt__['cmd.run_stdout'](cmd, python_shell=True)
pids = ''
for line in output.splitlines():
if 'status.pid' in line:
continue
if re.search(sig, line):
if pids:
pids += '\n'
pids += line.split()[1]
return pids
|
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1519-L1548
| null |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import logging
import fnmatch
import collections
import copy
import time
import logging
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.config
import salt.minion
import salt.utils.event
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__file__)
__virtualname__ = 'status'
__opts__ = {}
# Don't shadow built-in's.
__func_alias__ = {
'time_': 'time'
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Not all functions supported by Windows
'''
if salt.utils.platform.is_windows():
return False, 'Windows platform is not supported by this module'
return __virtualname__
def _number(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
if text.isdigit():
return int(text)
try:
return float(text)
except ValueError:
return text
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
'''
boot_secs = 0
res = __salt__['cmd.run_all']('ps -o etime= -p 1')
if res['retcode'] > 0:
raise CommandExecutionError('Unable to find boot_time for pid 1.')
bt_time = res['stdout']
days = bt_time.split('-')
hms = days[1].split(':')
boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2])
return boot_secs
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
'5-min': load_avg[2].strip(','),
'15-min': load_avg[3]}
def _aix_nproc():
'''
Return the maximun number of PROCESSES allowed per user on AIX
'''
nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split()
return _number(nprocs[1])
def procs():
'''
Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs
'''
# Get the user, pid and cmd
ret = {}
uind = 0
pind = 0
cind = 0
plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines()
guide = plines.pop(0).split()
if 'USER' in guide:
uind = guide.index('USER')
elif 'UID' in guide:
uind = guide.index('UID')
if 'PID' in guide:
pind = guide.index('PID')
if 'COMMAND' in guide:
cind = guide.index('COMMAND')
elif 'CMD' in guide:
cind = guide.index('CMD')
for line in plines:
if not line:
continue
comps = line.split()
ret[comps[pind]] = {'user': comps[uind],
'cmd': ' '.join(comps[cind:])}
return ret
def custom():
'''
Return a custom composite of status data and info for this minion,
based on the minion config file. An example config like might be::
status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ]
Where status refers to status.py, cpustats is the function
where we get our data, and custom is this function It is followed
by a list of keys that we want returned.
This function is meant to replace all_status(), which returns
anything and everything, which we probably don't want.
By default, nothing is returned. Warning: Depending on what you
include, there can be a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.custom
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
for key, val in six.iteritems(conf):
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123
for item in val:
ret[item] = vals[item]
return ret
def uptime():
'''
Return the uptime for this system.
.. versionchanged:: 2015.8.9
The uptime function was changed to return a dictionary of easy-to-read
key/value pairs containing uptime information, instead of the output
from a ``cmd.run`` call.
.. versionchanged:: 2016.11.0
Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.uptime
'''
curr_seconds = time.time()
# Get uptime in seconds
if salt.utils.platform.is_linux():
ut_path = "/proc/uptime"
if not os.path.exists(ut_path):
raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path))
with salt.utils.files.fopen(ut_path) as rfh:
seconds = int(float(rfh.read().split()[0]))
elif salt.utils.platform.is_sunos():
# note: some flavors/versions report the host uptime inside a zone
# https://support.oracle.com/epmos/faces/BugDisplay?id=15611584
res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')
if res['retcode'] > 0:
raise CommandExecutionError('The boot_time kstat was not found.')
seconds = int(curr_seconds - int(res['stdout'].split()[-1]))
elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
seconds = int(curr_seconds - int(bt_data))
elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():
# format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '')
uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])
seconds = int(curr_seconds - uptime['sec'])
elif salt.utils.platform.is_aix():
seconds = _get_boot_time_aix()
else:
return __salt__['cmd.run']('uptime')
# Setup datetime and timedelta objects
boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)
curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)
up_time = curr_time - boot_time
# Construct return information
ut_ret = {
'seconds': seconds,
'since_iso': boot_time.isoformat(),
'since_t': int(curr_seconds - seconds),
'days': up_time.days,
'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),
}
if salt.utils.path.which('who'):
who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s
ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))
return ut_ret
def loadavg():
'''
Return the load averages for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.loadavg
:raises CommandExecutionError: If the system cannot report loadaverages to Python
'''
if __grains__['kernel'] == 'AIX':
return _aix_loadavg()
try:
load_avg = os.getloadavg()
except AttributeError:
# Some UNIX-based operating systems do not have os.getloadavg()
raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')
return {'1-min': load_avg[0],
'5-min': load_avg[1],
'15-min': load_avg[2]}
def cpustats():
'''
Return the CPU stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpustats
'''
def linux_cpustats():
'''
linux specific implementation of cpustats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == 'cpu':
ret[comps[0]] = {'idle': _number(comps[4]),
'iowait': _number(comps[5]),
'irq': _number(comps[6]),
'nice': _number(comps[2]),
'softirq': _number(comps[7]),
'steal': _number(comps[8]),
'system': _number(comps[3]),
'user': _number(comps[1])}
elif comps[0] == 'intr':
ret[comps[0]] = {'total': _number(comps[1]),
'irqs': [_number(x) for x in comps[2:]]}
elif comps[0] == 'softirq':
ret[comps[0]] = {'total': _number(comps[1]),
'softirqs': [_number(x) for x in comps[2:]]}
else:
ret[comps[0]] = _number(comps[1])
return ret
def freebsd_cpustats():
'''
freebsd specific implementation of cpustats
'''
vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
vm0 = vmstat[0].split()
cpu0loc = vm0.index('cpu0')
vm1 = vmstat[1].split()
usloc = vm1.index('us')
vm2 = vmstat[2].split()
cpuctr = 0
ret = {}
for cpu in vm0[cpu0loc:]:
ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
cpuctr += 1
return ret
def sunos_cpustats():
'''
sunos specific implementation of cpustats
'''
mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
fields = mpstat[0].split()
ret = {}
for cpu in mpstat:
if cpu.startswith('CPU'):
continue
cpu = cpu.split()
ret[_number(cpu[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
return ret
def aix_cpustats():
'''
AIX specific implementation of cpustats
'''
ret = {}
ret['mpstat'] = []
procn = None
fields = []
for line in __salt__['cmd.run']('mpstat -a').splitlines():
if not line:
continue
procn = len(ret['mpstat'])
if line.startswith('System'):
comps = line.split(':')
ret['mpstat'].append({})
ret['mpstat'][procn]['system'] = {}
cpu_comps = comps[1].split()
for i in range(0, len(cpu_comps)):
cpu_vals = cpu_comps[i].split('=')
ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]
if line.startswith('cpu'):
fields = line.split()
continue
if fields:
cpustat = line.split()
ret[_number(cpustat[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])
return ret
def openbsd_cpustats():
'''
openbsd specific implementation of cpustats
'''
systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
fields = systat[3].split()
ret = {}
for cpu in systat[4:]:
cpu_line = cpu.split()
cpu_idx = cpu_line[0]
ret[cpu_idx] = {}
for idx, field in enumerate(fields[1:]):
ret[cpu_idx][field] = cpu_line[idx+1]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_cpustats,
'FreeBSD': freebsd_cpustats,
'OpenBSD': openbsd_cpustats,
'SunOS': sunos_cpustats,
'AIX': aix_cpustats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''
linux specific implementation of meminfo
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {
'value': comps[1],
}
if len(comps) > 2:
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'''
freebsd specific implementation of meminfo
'''
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
# Special handling for vm.total as it's especially important
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
def aix_meminfo():
'''
AIX specific implementation of meminfo
'''
ret = {}
ret['svmon'] = []
ret['vmstat'] = []
procn = None
fields = []
pagesize_flag = False
for line in __salt__['cmd.run']('svmon -G').splitlines():
# Note: svmon is per-system
# size inuse free pin virtual mmode
#memory 1048576 1039740 8836 285078 474993 Ded
#pg space 917504 2574
#
# work pers clnt other
#pin 248379 0 2107 34592
#in use 474993 0 564747
#
#PageSize PoolSize inuse pgsp pin virtual
#s 4 KB - 666956 2574 60726 102209
#m 64 KB - 23299 0 14022 23299
if not line:
continue
if re.match(r'\s', line):
# assume fields line
fields = line.split()
continue
if line.startswith('memory') or line.startswith('pin'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i + 1:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
continue
if line.startswith('pg space') or line.startswith('in use'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
pg_space = '{0} {1}'.format(comps[0], comps[1])
ret['svmon'][procn][pg_space] = {}
for i in range(0, len(fields)):
if len(comps) > i + 2:
ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
continue
if line.startswith('PageSize'):
fields = line.split()
pagesize_flag = False
continue
if pagesize_flag:
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
continue
for line in __salt__['cmd.run']('vmstat -v').splitlines():
# Note: vmstat is per-system
if not line:
continue
procn = len(ret['vmstat'])
ret['vmstat'].append({})
comps = line.lstrip().split(' ', 1)
ret['vmstat'][procn][comps[1]] = comps[0]
return ret
def openbsd_meminfo():
'''
openbsd specific implementation of meminfo
'''
vmstat = __salt__['cmd.run']('vmstat').splitlines()
# We're only interested in memory and page values which are printed
# as subsequent fields.
fields = ['active virtual pages', 'free list size', 'page faults',
'pages reclaimed', 'pages paged in', 'pages paged out',
'pages freed', 'pages scanned']
data = vmstat[2].split()[2:10]
ret = dict(zip(fields, data))
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_meminfo,
'FreeBSD': freebsd_meminfo,
'OpenBSD': openbsd_meminfo,
'AIX': aix_meminfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def cpuinfo():
'''
.. versionchanged:: 2016.3.2
Return the CPU info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for NetBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpuinfo
'''
def linux_cpuinfo():
'''
linux specific cpuinfo implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
if comps[0] == 'flags':
ret[comps[0]] = comps[1].split()
else:
ret[comps[0]] = comps[1].strip()
return ret
def bsd_cpuinfo():
'''
bsd specific cpuinfo implementation
'''
bsd_cmd = 'sysctl hw.model hw.ncpu'
ret = {}
if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:
sep = '='
else:
sep = ':'
for line in __salt__['cmd.run'](bsd_cmd).splitlines():
if not line:
continue
comps = line.split(sep)
comps[0] = comps[0].strip()
ret[comps[0]] = comps[1].strip()
return ret
def sunos_cpuinfo():
'''
sunos specific cpuinfo implementation
'''
ret = {}
ret['isainfo'] = {}
for line in __salt__['cmd.run']('isainfo -x').splitlines():
# Note: isainfo is per-system and not per-cpu
# Output Example:
#amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu
#i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())
ret['psrinfo'] = []
procn = None
for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():
# Output Example:
#The physical processor has 6 cores and 12 virtual processors (0-5 12-17)
# The core has 2 virtual processors (0 12)
# The core has 2 virtual processors (1 13)
# The core has 2 virtual processors (2 14)
# The core has 2 virtual processors (3 15)
# The core has 2 virtual processors (4 16)
# The core has 2 virtual processors (5 17)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#The physical processor has 6 cores and 12 virtual processors (6-11 18-23)
# The core has 2 virtual processors (6 18)
# The core has 2 virtual processors (7 19)
# The core has 2 virtual processors (8 20)
# The core has 2 virtual processors (9 21)
# The core has 2 virtual processors (10 22)
# The core has 2 virtual processors (11 23)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#
# Output Example 2:
#The physical processor has 4 virtual processors (0-3)
# x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)
# Intel(r) Atom(tm) CPU C2558 @ 2.40GHz
if not line:
continue
if line.startswith('The physical processor'):
procn = len(ret['psrinfo'])
line = line.split()
ret['psrinfo'].append({})
if 'cores' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])
ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])
elif 'virtual' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])
elif line.startswith(' ' * 6): # 3x2 space indent
ret['psrinfo'][procn]['name'] = line.strip()
elif line.startswith(' ' * 4): # 2x2 space indent
line = line.strip().split()
ret['psrinfo'][procn]['vendor'] = line[1][1:]
ret['psrinfo'][procn]['family'] = _number(line[4])
ret['psrinfo'][procn]['model'] = _number(line[6])
ret['psrinfo'][procn]['step'] = _number(line[8])
ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1])
return ret
def aix_cpuinfo():
'''
AIX specific cpuinfo implementation
'''
ret = {}
ret['prtconf'] = []
ret['lparstat'] = []
procn = None
for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#prtconf | grep -i "Processor"
#Processor Type: PowerPC_POWER7
#Processor Implementation Mode: POWER 7
#Processor Version: PV_7_Compat
#Number Of Processors: 2
#Processor Clock Speed: 3000 MHz
# Model Implementation: Multiple Processor, PCI bus
# + proc0 Processor
# + proc4 Processor
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('Processor') or line.startswith('Number'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#CPU Type: 64-bit
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('CPU'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():
# Note: lparstat is per-system and not per-cpu
# Output Example:
#Online Virtual CPUs : 2
#Maximum Virtual CPUs : 2
#Minimum Virtual CPUs : 1
#Maximum Physical CPUs in system : 32
#Active Physical CPUs in system : 32
#Active CPUs in Pool : 32
#Shared Physical CPUs in system : 32
#Physical CPU Percentage : 25.00%
#Desired Virtual CPUs : 2
if not line:
continue
procn = len(ret['lparstat'])
ret['lparstat'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['lparstat'][procn][comps[0]] = comps[1]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_cpuinfo,
'FreeBSD': bsd_cpuinfo,
'NetBSD': bsd_cpuinfo,
'OpenBSD': bsd_cpuinfo,
'SunOS': sunos_cpuinfo,
'AIX': aix_cpuinfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific implementation of diskstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[2]] = {
'major': _number(comps[0]),
'minor': _number(comps[1]),
'device': _number(comps[2]),
'reads_issued': _number(comps[3]),
'reads_merged': _number(comps[4]),
'sectors_read': _number(comps[5]),
'ms_spent_reading': _number(comps[6]),
'writes_completed': _number(comps[7]),
'writes_merged': _number(comps[8]),
'sectors_written': _number(comps[9]),
'ms_spent_writing': _number(comps[10]),
'io_in_progress': _number(comps[11]),
'ms_spent_in_io': _number(comps[12]),
'weighted_ms_spent_in_io': _number(comps[13])
}
return ret
def generic_diskstats():
'''
generic implementation of diskstats
note: freebsd and sunos
'''
ret = {}
iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
header = iostat[1]
for line in iostat[2:]:
comps = line.split()
ret[comps[0]] = {}
for metric, value in zip(header.split()[1:], comps[1:]):
ret[comps[0]][metric] = _number(value)
return ret
def aix_diskstats():
'''
AIX specific implementation of diskstats
'''
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
for line in __salt__['cmd.run']('iostat -dDV').splitlines():
# Note: iostat -dDV is per-system
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk0 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.8 0.0 0.0 0.8
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 2.5 0.3 12.4 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.3 0.2 0.7 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.3 0.0 5.3 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#have new disk
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()
ret[disk_name] = []
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
else:
comps = line.split()
for i in range(0, len(fields)):
if len(comps) > i:
ret[disk_name][procn][disk_mode][fields[i]] = comps[i]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_diskstats,
'FreeBSD': generic_diskstats,
'SunOS': generic_diskstats,
'AIX': aix_diskstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskusage(*args):
'''
Return the disk usage for this minion
Usage::
salt '*' status.diskusage [paths and/or filesystem types]
CLI Example:
.. code-block:: bash
salt '*' status.diskusage # usage for all filesystems
salt '*' status.diskusage / /tmp # usage for / and /tmp
salt '*' status.diskusage ext? # usage for ext[234] filesystems
salt '*' status.diskusage / ext? # usage for / and all ext filesystems
'''
selected = set()
fstypes = set()
if not args:
# select all filesystems
fstypes.add('*')
else:
for arg in args:
if arg.startswith('/'):
# select path
selected.add(arg)
else:
# select fstype
fstypes.add(arg)
if fstypes:
# determine which mount points host the specified fstypes
regex = re.compile(
'|'.join(
fnmatch.translate(fstype).format('(%s)') for fstype in fstypes
)
)
# ifile source of data varies with OS, otherwise all the same
if __grains__['kernel'] == 'Linux':
try:
with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:
ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()
except OSError:
return {}
elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):
ifile = __salt__['cmd.run']('mount -p').splitlines()
else:
raise CommandExecutionError('status.diskusage not yet supported on this platform')
for line in ifile:
comps = line.split()
if __grains__['kernel'] == 'SunOS':
if len(comps) >= 4:
mntpt = comps[2]
fstype = comps[3]
if regex.match(fstype):
selected.add(mntpt)
else:
if len(comps) >= 3:
mntpt = comps[1]
fstype = comps[2]
if regex.match(fstype):
selected.add(mntpt)
# query the filesystems disk usage
ret = {}
for path in selected:
fsstats = os.statvfs(path)
blksz = fsstats.f_bsize
available = fsstats.f_bavail * blksz
total = fsstats.f_blocks * blksz
ret[path] = {"available": available, "total": total}
return ret
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specific implementation of vmstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[0]] = _number(comps[1])
return ret
def generic_vmstats():
'''
generic implementation of vmstats
note: works on FreeBSD, SunOS and OpenBSD (possibly others)
'''
ret = {}
for line in __salt__['cmd.run']('vmstat -s').splitlines():
comps = line.split()
if comps[0].isdigit():
ret[' '.join(comps[1:])] = _number(comps[0].strip())
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_vmstats,
'FreeBSD': generic_vmstats,
'OpenBSD': generic_vmstats,
'SunOS': generic_vmstats,
'AIX': generic_vmstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def nproc():
'''
Return the number of processing units available on this system
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for Darwin, FreeBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.nproc
'''
def linux_nproc():
'''
linux specific implementation of nproc
'''
try:
return _number(__salt__['cmd.run']('nproc').strip())
except ValueError:
return 0
def generic_nproc():
'''
generic implementation of nproc
'''
ncpu_data = __salt__['sysctl.get']('hw.ncpu')
if not ncpu_data:
# We need at least one CPU to run
return 1
else:
return _number(ncpu_data)
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_nproc,
'Darwin': generic_nproc,
'FreeBSD': generic_nproc,
'OpenBSD': generic_nproc,
'AIX': _aix_nproc,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netstats():
'''
Return the network stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.netstats
'''
def linux_netstats():
'''
linux specific netstats implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
headers = ['']
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
else:
headers = comps
return ret
def freebsd_netstats():
return bsd_netstats()
def bsd_netstats():
'''
bsd specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
if line.startswith('\t\t'):
continue # Skip, too detailed
if not line.startswith('\t'):
key = line.split()[0].replace(':', '')
ret[key] = {}
else:
comps = line.split()
if comps[0].isdigit():
ret[key][' '.join(comps[1:])] = comps[0]
return ret
def sunos_netstats():
'''
sunos specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
line = line.replace('=', ' = ').split()
if len(line) > 6:
line.pop(0)
if '=' in line:
if len(line) >= 3:
if line[2].isdigit() or line[2][0] == '-':
line[2] = _number(line[2])
ret[line[0]] = line[2]
if len(line) >= 6:
if line[5].isdigit() or line[5][0] == '-':
line[5] = _number(line[5])
ret[line[3]] = line[5]
return ret
def aix_netstats():
'''
AIX specific netstats implementation
'''
ret = {}
fields = []
procn = None
proto_name = None
for line in __salt__['cmd.run']('netstat -s').splitlines():
if not line:
continue
if not re.match(r'\s', line) and ':' in line:
comps = line.split(':')
proto_name = comps[0]
ret[proto_name] = []
procn = len(ret[proto_name])
ret[proto_name].append({})
continue
else:
comps = line.split()
comps[0] = comps[0].strip()
if comps[0].isdigit():
ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])
else:
continue
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netstats,
'FreeBSD': bsd_netstats,
'OpenBSD': bsd_netstats,
'SunOS': sunos_netstats,
'AIX': aix_netstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific implementation of netdev
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
if line.find(':') < 0:
continue
comps = line.split()
# Fix lines like eth0:9999..'
comps[0] = line.split(':')[0].strip()
# Support lines both like eth0:999 and eth0: 9999
comps.insert(1, line.split(':')[1].strip().split()[0])
ret[comps[0]] = {'iface': comps[0],
'rx_bytes': _number(comps[2]),
'rx_compressed': _number(comps[8]),
'rx_drop': _number(comps[5]),
'rx_errs': _number(comps[4]),
'rx_fifo': _number(comps[6]),
'rx_frame': _number(comps[7]),
'rx_multicast': _number(comps[9]),
'rx_packets': _number(comps[3]),
'tx_bytes': _number(comps[10]),
'tx_carrier': _number(comps[16]),
'tx_colls': _number(comps[15]),
'tx_compressed': _number(comps[17]),
'tx_drop': _number(comps[13]),
'tx_errs': _number(comps[12]),
'tx_fifo': _number(comps[14]),
'tx_packets': _number(comps[11])}
return ret
def freebsd_netdev():
'''
freebsd specific implementation of netdev
'''
_dict_tree = lambda: collections.defaultdict(_dict_tree)
ret = _dict_tree()
netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()
netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]
header = netstat[0].split()
for line in netstat[1:]:
comps = line.split()
for i in range(4, 13): # The columns we want
ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])
return ret
def sunos_netdev():
'''
sunos specific implementation of netdev
'''
ret = {}
##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:
# fetch device info
netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()
# prepare data
netstat_ipv4[0] = netstat_ipv4[0].split()
netstat_ipv4[1] = netstat_ipv4[1].split()
netstat_ipv6[0] = netstat_ipv6[0].split()
netstat_ipv6[1] = netstat_ipv6[1].split()
# add data
ret[dev] = {}
for i in range(len(netstat_ipv4[0])-1):
if netstat_ipv4[0][i] == 'Name':
continue
if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]
else:
ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])
for i in range(len(netstat_ipv6[0])-1):
if netstat_ipv6[0][i] == 'Name':
continue
if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]
else:
ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])
return ret
def aix_netdev():
'''
AIX specific implementation of netdev
'''
ret = {}
fields = []
procn = None
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():
# fetch device info
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0
#en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0
netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()
# add data
ret[dev] = []
for line in netstat_ipv4:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv4'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv4'][fields[i]] = comps[i]
for line in netstat_ipv6:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv6'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv6'][fields[i]] = comps[i]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netdev,
'FreeBSD': freebsd_netdev,
'SunOS': sunos_netdev,
'AIX': aix_netdev,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def w(): # pylint: disable=C0103
'''
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
'''
def linux_w():
'''
Linux specific implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -fh').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'idle': comps[3],
'jcpu': comps[4],
'login': comps[2],
'pcpu': comps[5],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[6:])}
user_list.append(rec)
return user_list
def bsd_w():
'''
Generic BSD implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -h').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'from': comps[2],
'idle': comps[4],
'login': comps[3],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[5:])}
user_list.append(rec)
return user_list
# dict that returns a function that does the right thing per platform
get_version = {
'Darwin': bsd_w,
'FreeBSD': bsd_w,
'Linux': linux_w,
'OpenBSD': bsd_w,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def all_status():
'''
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
'''
return {'cpuinfo': cpuinfo(),
'cpustats': cpustats(),
'diskstats': diskstats(),
'diskusage': diskusage(),
'loadavg': loadavg(),
'meminfo': meminfo(),
'netdev': netdev(),
'netstats': netstats(),
'uptime': uptime(),
'vmstats': vmstats(),
'w': w()}
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
'''
linux specific implementation of version
'''
try:
with salt.utils.files.fopen('/proc/version', 'r') as fp_:
return salt.utils.stringutils.to_unicode(fp_.read()).strip()
except IOError:
return {}
def bsd_version():
'''
bsd specific implementation of version
'''
return __salt__['cmd.run']('sysctl -n kern.version')
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_version,
'FreeBSD': bsd_version,
'OpenBSD': bsd_version,
'AIX': lambda: __salt__['cmd.run']('oslevel -s'),
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def master(master=None, connected=True):
'''
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
master_ips = None
if master:
master_ips = salt.utils.network.host_to_ips(master)
if not master_ips:
return
master_connection_status = False
port = __salt__['config.get']('publish_port', default=4505)
connected_ips = salt.utils.network.remote_port_tcp(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
def ping_master(master):
'''
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
'''
if master is None or master == '':
return False
opts = copy.deepcopy(__opts__)
opts['master'] = master
if 'master_ip' in opts: # avoid 'master ip changed' warning
del opts['master_ip']
opts.update(salt.minion.prep_ip_port(opts))
try:
opts.update(salt.minion.resolve_dns(opts, fallback=False))
except Exception:
return False
timeout = opts.get('auth_timeout', 60)
load = {'cmd': 'ping'}
result = False
channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear')
try:
payload = channel.send(load, tries=0, timeout=timeout)
result = True
except Exception as e:
pass
if result:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
event.fire_event({'master': master}, salt.minion.master_event(type='failback'))
return result
def proxy_reconnect(proxy_name, opts=None):
'''
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
'''
if not opts:
opts = __opts__
if 'proxy' not in opts:
return False # fail
proxy_keepalive_fn = proxy_name+'.alive'
if proxy_keepalive_fn not in __proxy__:
return False # fail
is_alive = __proxy__[proxy_keepalive_fn](opts)
if not is_alive:
minion_id = opts.get('proxyid', '') or opts.get('id', '')
log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name)
__proxy__[proxy_name+'.shutdown'](opts) # safely close connection
__proxy__[proxy_name+'.init'](opts) # reopen connection
log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name)
return True # success
def time_(format='%A, %d. %B %Y %I:%M%p'):
'''
.. versionadded:: 2016.3.0
Return the current time on the minion,
formatted based on the format parameter.
Default date format: Monday, 27. July 2015 07:55AM
CLI Example:
.. code-block:: bash
salt '*' status.time
salt '*' status.time '%s'
'''
dt = datetime.datetime.today()
return dt.strftime(format)
|
saltstack/salt
|
salt/modules/status.py
|
version
|
python
|
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
'''
linux specific implementation of version
'''
try:
with salt.utils.files.fopen('/proc/version', 'r') as fp_:
return salt.utils.stringutils.to_unicode(fp_.read()).strip()
except IOError:
return {}
def bsd_version():
'''
bsd specific implementation of version
'''
return __salt__['cmd.run']('sysctl -n kern.version')
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_version,
'FreeBSD': bsd_version,
'OpenBSD': bsd_version,
'AIX': lambda: __salt__['cmd.run']('oslevel -s'),
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
|
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1551-L1592
| null |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import logging
import fnmatch
import collections
import copy
import time
import logging
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.config
import salt.minion
import salt.utils.event
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__file__)
__virtualname__ = 'status'
__opts__ = {}
# Don't shadow built-in's.
__func_alias__ = {
'time_': 'time'
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Not all functions supported by Windows
'''
if salt.utils.platform.is_windows():
return False, 'Windows platform is not supported by this module'
return __virtualname__
def _number(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
if text.isdigit():
return int(text)
try:
return float(text)
except ValueError:
return text
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
'''
boot_secs = 0
res = __salt__['cmd.run_all']('ps -o etime= -p 1')
if res['retcode'] > 0:
raise CommandExecutionError('Unable to find boot_time for pid 1.')
bt_time = res['stdout']
days = bt_time.split('-')
hms = days[1].split(':')
boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2])
return boot_secs
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
'5-min': load_avg[2].strip(','),
'15-min': load_avg[3]}
def _aix_nproc():
'''
Return the maximun number of PROCESSES allowed per user on AIX
'''
nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split()
return _number(nprocs[1])
def procs():
'''
Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs
'''
# Get the user, pid and cmd
ret = {}
uind = 0
pind = 0
cind = 0
plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines()
guide = plines.pop(0).split()
if 'USER' in guide:
uind = guide.index('USER')
elif 'UID' in guide:
uind = guide.index('UID')
if 'PID' in guide:
pind = guide.index('PID')
if 'COMMAND' in guide:
cind = guide.index('COMMAND')
elif 'CMD' in guide:
cind = guide.index('CMD')
for line in plines:
if not line:
continue
comps = line.split()
ret[comps[pind]] = {'user': comps[uind],
'cmd': ' '.join(comps[cind:])}
return ret
def custom():
'''
Return a custom composite of status data and info for this minion,
based on the minion config file. An example config like might be::
status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ]
Where status refers to status.py, cpustats is the function
where we get our data, and custom is this function It is followed
by a list of keys that we want returned.
This function is meant to replace all_status(), which returns
anything and everything, which we probably don't want.
By default, nothing is returned. Warning: Depending on what you
include, there can be a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.custom
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
for key, val in six.iteritems(conf):
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123
for item in val:
ret[item] = vals[item]
return ret
def uptime():
'''
Return the uptime for this system.
.. versionchanged:: 2015.8.9
The uptime function was changed to return a dictionary of easy-to-read
key/value pairs containing uptime information, instead of the output
from a ``cmd.run`` call.
.. versionchanged:: 2016.11.0
Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.uptime
'''
curr_seconds = time.time()
# Get uptime in seconds
if salt.utils.platform.is_linux():
ut_path = "/proc/uptime"
if not os.path.exists(ut_path):
raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path))
with salt.utils.files.fopen(ut_path) as rfh:
seconds = int(float(rfh.read().split()[0]))
elif salt.utils.platform.is_sunos():
# note: some flavors/versions report the host uptime inside a zone
# https://support.oracle.com/epmos/faces/BugDisplay?id=15611584
res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')
if res['retcode'] > 0:
raise CommandExecutionError('The boot_time kstat was not found.')
seconds = int(curr_seconds - int(res['stdout'].split()[-1]))
elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
seconds = int(curr_seconds - int(bt_data))
elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():
# format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '')
uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])
seconds = int(curr_seconds - uptime['sec'])
elif salt.utils.platform.is_aix():
seconds = _get_boot_time_aix()
else:
return __salt__['cmd.run']('uptime')
# Setup datetime and timedelta objects
boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)
curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)
up_time = curr_time - boot_time
# Construct return information
ut_ret = {
'seconds': seconds,
'since_iso': boot_time.isoformat(),
'since_t': int(curr_seconds - seconds),
'days': up_time.days,
'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),
}
if salt.utils.path.which('who'):
who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s
ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))
return ut_ret
def loadavg():
'''
Return the load averages for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.loadavg
:raises CommandExecutionError: If the system cannot report loadaverages to Python
'''
if __grains__['kernel'] == 'AIX':
return _aix_loadavg()
try:
load_avg = os.getloadavg()
except AttributeError:
# Some UNIX-based operating systems do not have os.getloadavg()
raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')
return {'1-min': load_avg[0],
'5-min': load_avg[1],
'15-min': load_avg[2]}
def cpustats():
'''
Return the CPU stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpustats
'''
def linux_cpustats():
'''
linux specific implementation of cpustats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == 'cpu':
ret[comps[0]] = {'idle': _number(comps[4]),
'iowait': _number(comps[5]),
'irq': _number(comps[6]),
'nice': _number(comps[2]),
'softirq': _number(comps[7]),
'steal': _number(comps[8]),
'system': _number(comps[3]),
'user': _number(comps[1])}
elif comps[0] == 'intr':
ret[comps[0]] = {'total': _number(comps[1]),
'irqs': [_number(x) for x in comps[2:]]}
elif comps[0] == 'softirq':
ret[comps[0]] = {'total': _number(comps[1]),
'softirqs': [_number(x) for x in comps[2:]]}
else:
ret[comps[0]] = _number(comps[1])
return ret
def freebsd_cpustats():
'''
freebsd specific implementation of cpustats
'''
vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
vm0 = vmstat[0].split()
cpu0loc = vm0.index('cpu0')
vm1 = vmstat[1].split()
usloc = vm1.index('us')
vm2 = vmstat[2].split()
cpuctr = 0
ret = {}
for cpu in vm0[cpu0loc:]:
ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
cpuctr += 1
return ret
def sunos_cpustats():
'''
sunos specific implementation of cpustats
'''
mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
fields = mpstat[0].split()
ret = {}
for cpu in mpstat:
if cpu.startswith('CPU'):
continue
cpu = cpu.split()
ret[_number(cpu[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
return ret
def aix_cpustats():
'''
AIX specific implementation of cpustats
'''
ret = {}
ret['mpstat'] = []
procn = None
fields = []
for line in __salt__['cmd.run']('mpstat -a').splitlines():
if not line:
continue
procn = len(ret['mpstat'])
if line.startswith('System'):
comps = line.split(':')
ret['mpstat'].append({})
ret['mpstat'][procn]['system'] = {}
cpu_comps = comps[1].split()
for i in range(0, len(cpu_comps)):
cpu_vals = cpu_comps[i].split('=')
ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]
if line.startswith('cpu'):
fields = line.split()
continue
if fields:
cpustat = line.split()
ret[_number(cpustat[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])
return ret
def openbsd_cpustats():
'''
openbsd specific implementation of cpustats
'''
systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
fields = systat[3].split()
ret = {}
for cpu in systat[4:]:
cpu_line = cpu.split()
cpu_idx = cpu_line[0]
ret[cpu_idx] = {}
for idx, field in enumerate(fields[1:]):
ret[cpu_idx][field] = cpu_line[idx+1]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_cpustats,
'FreeBSD': freebsd_cpustats,
'OpenBSD': openbsd_cpustats,
'SunOS': sunos_cpustats,
'AIX': aix_cpustats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''
linux specific implementation of meminfo
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {
'value': comps[1],
}
if len(comps) > 2:
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'''
freebsd specific implementation of meminfo
'''
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
# Special handling for vm.total as it's especially important
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
def aix_meminfo():
'''
AIX specific implementation of meminfo
'''
ret = {}
ret['svmon'] = []
ret['vmstat'] = []
procn = None
fields = []
pagesize_flag = False
for line in __salt__['cmd.run']('svmon -G').splitlines():
# Note: svmon is per-system
# size inuse free pin virtual mmode
#memory 1048576 1039740 8836 285078 474993 Ded
#pg space 917504 2574
#
# work pers clnt other
#pin 248379 0 2107 34592
#in use 474993 0 564747
#
#PageSize PoolSize inuse pgsp pin virtual
#s 4 KB - 666956 2574 60726 102209
#m 64 KB - 23299 0 14022 23299
if not line:
continue
if re.match(r'\s', line):
# assume fields line
fields = line.split()
continue
if line.startswith('memory') or line.startswith('pin'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i + 1:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
continue
if line.startswith('pg space') or line.startswith('in use'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
pg_space = '{0} {1}'.format(comps[0], comps[1])
ret['svmon'][procn][pg_space] = {}
for i in range(0, len(fields)):
if len(comps) > i + 2:
ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
continue
if line.startswith('PageSize'):
fields = line.split()
pagesize_flag = False
continue
if pagesize_flag:
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
continue
for line in __salt__['cmd.run']('vmstat -v').splitlines():
# Note: vmstat is per-system
if not line:
continue
procn = len(ret['vmstat'])
ret['vmstat'].append({})
comps = line.lstrip().split(' ', 1)
ret['vmstat'][procn][comps[1]] = comps[0]
return ret
def openbsd_meminfo():
'''
openbsd specific implementation of meminfo
'''
vmstat = __salt__['cmd.run']('vmstat').splitlines()
# We're only interested in memory and page values which are printed
# as subsequent fields.
fields = ['active virtual pages', 'free list size', 'page faults',
'pages reclaimed', 'pages paged in', 'pages paged out',
'pages freed', 'pages scanned']
data = vmstat[2].split()[2:10]
ret = dict(zip(fields, data))
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_meminfo,
'FreeBSD': freebsd_meminfo,
'OpenBSD': openbsd_meminfo,
'AIX': aix_meminfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def cpuinfo():
'''
.. versionchanged:: 2016.3.2
Return the CPU info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for NetBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpuinfo
'''
def linux_cpuinfo():
'''
linux specific cpuinfo implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
if comps[0] == 'flags':
ret[comps[0]] = comps[1].split()
else:
ret[comps[0]] = comps[1].strip()
return ret
def bsd_cpuinfo():
'''
bsd specific cpuinfo implementation
'''
bsd_cmd = 'sysctl hw.model hw.ncpu'
ret = {}
if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:
sep = '='
else:
sep = ':'
for line in __salt__['cmd.run'](bsd_cmd).splitlines():
if not line:
continue
comps = line.split(sep)
comps[0] = comps[0].strip()
ret[comps[0]] = comps[1].strip()
return ret
def sunos_cpuinfo():
'''
sunos specific cpuinfo implementation
'''
ret = {}
ret['isainfo'] = {}
for line in __salt__['cmd.run']('isainfo -x').splitlines():
# Note: isainfo is per-system and not per-cpu
# Output Example:
#amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu
#i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())
ret['psrinfo'] = []
procn = None
for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():
# Output Example:
#The physical processor has 6 cores and 12 virtual processors (0-5 12-17)
# The core has 2 virtual processors (0 12)
# The core has 2 virtual processors (1 13)
# The core has 2 virtual processors (2 14)
# The core has 2 virtual processors (3 15)
# The core has 2 virtual processors (4 16)
# The core has 2 virtual processors (5 17)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#The physical processor has 6 cores and 12 virtual processors (6-11 18-23)
# The core has 2 virtual processors (6 18)
# The core has 2 virtual processors (7 19)
# The core has 2 virtual processors (8 20)
# The core has 2 virtual processors (9 21)
# The core has 2 virtual processors (10 22)
# The core has 2 virtual processors (11 23)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#
# Output Example 2:
#The physical processor has 4 virtual processors (0-3)
# x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)
# Intel(r) Atom(tm) CPU C2558 @ 2.40GHz
if not line:
continue
if line.startswith('The physical processor'):
procn = len(ret['psrinfo'])
line = line.split()
ret['psrinfo'].append({})
if 'cores' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])
ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])
elif 'virtual' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])
elif line.startswith(' ' * 6): # 3x2 space indent
ret['psrinfo'][procn]['name'] = line.strip()
elif line.startswith(' ' * 4): # 2x2 space indent
line = line.strip().split()
ret['psrinfo'][procn]['vendor'] = line[1][1:]
ret['psrinfo'][procn]['family'] = _number(line[4])
ret['psrinfo'][procn]['model'] = _number(line[6])
ret['psrinfo'][procn]['step'] = _number(line[8])
ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1])
return ret
def aix_cpuinfo():
'''
AIX specific cpuinfo implementation
'''
ret = {}
ret['prtconf'] = []
ret['lparstat'] = []
procn = None
for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#prtconf | grep -i "Processor"
#Processor Type: PowerPC_POWER7
#Processor Implementation Mode: POWER 7
#Processor Version: PV_7_Compat
#Number Of Processors: 2
#Processor Clock Speed: 3000 MHz
# Model Implementation: Multiple Processor, PCI bus
# + proc0 Processor
# + proc4 Processor
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('Processor') or line.startswith('Number'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#CPU Type: 64-bit
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('CPU'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():
# Note: lparstat is per-system and not per-cpu
# Output Example:
#Online Virtual CPUs : 2
#Maximum Virtual CPUs : 2
#Minimum Virtual CPUs : 1
#Maximum Physical CPUs in system : 32
#Active Physical CPUs in system : 32
#Active CPUs in Pool : 32
#Shared Physical CPUs in system : 32
#Physical CPU Percentage : 25.00%
#Desired Virtual CPUs : 2
if not line:
continue
procn = len(ret['lparstat'])
ret['lparstat'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['lparstat'][procn][comps[0]] = comps[1]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_cpuinfo,
'FreeBSD': bsd_cpuinfo,
'NetBSD': bsd_cpuinfo,
'OpenBSD': bsd_cpuinfo,
'SunOS': sunos_cpuinfo,
'AIX': aix_cpuinfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific implementation of diskstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[2]] = {
'major': _number(comps[0]),
'minor': _number(comps[1]),
'device': _number(comps[2]),
'reads_issued': _number(comps[3]),
'reads_merged': _number(comps[4]),
'sectors_read': _number(comps[5]),
'ms_spent_reading': _number(comps[6]),
'writes_completed': _number(comps[7]),
'writes_merged': _number(comps[8]),
'sectors_written': _number(comps[9]),
'ms_spent_writing': _number(comps[10]),
'io_in_progress': _number(comps[11]),
'ms_spent_in_io': _number(comps[12]),
'weighted_ms_spent_in_io': _number(comps[13])
}
return ret
def generic_diskstats():
'''
generic implementation of diskstats
note: freebsd and sunos
'''
ret = {}
iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
header = iostat[1]
for line in iostat[2:]:
comps = line.split()
ret[comps[0]] = {}
for metric, value in zip(header.split()[1:], comps[1:]):
ret[comps[0]][metric] = _number(value)
return ret
def aix_diskstats():
'''
AIX specific implementation of diskstats
'''
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
for line in __salt__['cmd.run']('iostat -dDV').splitlines():
# Note: iostat -dDV is per-system
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk0 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.8 0.0 0.0 0.8
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 2.5 0.3 12.4 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.3 0.2 0.7 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.3 0.0 5.3 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#have new disk
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()
ret[disk_name] = []
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
else:
comps = line.split()
for i in range(0, len(fields)):
if len(comps) > i:
ret[disk_name][procn][disk_mode][fields[i]] = comps[i]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_diskstats,
'FreeBSD': generic_diskstats,
'SunOS': generic_diskstats,
'AIX': aix_diskstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskusage(*args):
'''
Return the disk usage for this minion
Usage::
salt '*' status.diskusage [paths and/or filesystem types]
CLI Example:
.. code-block:: bash
salt '*' status.diskusage # usage for all filesystems
salt '*' status.diskusage / /tmp # usage for / and /tmp
salt '*' status.diskusage ext? # usage for ext[234] filesystems
salt '*' status.diskusage / ext? # usage for / and all ext filesystems
'''
selected = set()
fstypes = set()
if not args:
# select all filesystems
fstypes.add('*')
else:
for arg in args:
if arg.startswith('/'):
# select path
selected.add(arg)
else:
# select fstype
fstypes.add(arg)
if fstypes:
# determine which mount points host the specified fstypes
regex = re.compile(
'|'.join(
fnmatch.translate(fstype).format('(%s)') for fstype in fstypes
)
)
# ifile source of data varies with OS, otherwise all the same
if __grains__['kernel'] == 'Linux':
try:
with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:
ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()
except OSError:
return {}
elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):
ifile = __salt__['cmd.run']('mount -p').splitlines()
else:
raise CommandExecutionError('status.diskusage not yet supported on this platform')
for line in ifile:
comps = line.split()
if __grains__['kernel'] == 'SunOS':
if len(comps) >= 4:
mntpt = comps[2]
fstype = comps[3]
if regex.match(fstype):
selected.add(mntpt)
else:
if len(comps) >= 3:
mntpt = comps[1]
fstype = comps[2]
if regex.match(fstype):
selected.add(mntpt)
# query the filesystems disk usage
ret = {}
for path in selected:
fsstats = os.statvfs(path)
blksz = fsstats.f_bsize
available = fsstats.f_bavail * blksz
total = fsstats.f_blocks * blksz
ret[path] = {"available": available, "total": total}
return ret
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specific implementation of vmstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[0]] = _number(comps[1])
return ret
def generic_vmstats():
'''
generic implementation of vmstats
note: works on FreeBSD, SunOS and OpenBSD (possibly others)
'''
ret = {}
for line in __salt__['cmd.run']('vmstat -s').splitlines():
comps = line.split()
if comps[0].isdigit():
ret[' '.join(comps[1:])] = _number(comps[0].strip())
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_vmstats,
'FreeBSD': generic_vmstats,
'OpenBSD': generic_vmstats,
'SunOS': generic_vmstats,
'AIX': generic_vmstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def nproc():
'''
Return the number of processing units available on this system
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for Darwin, FreeBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.nproc
'''
def linux_nproc():
'''
linux specific implementation of nproc
'''
try:
return _number(__salt__['cmd.run']('nproc').strip())
except ValueError:
return 0
def generic_nproc():
'''
generic implementation of nproc
'''
ncpu_data = __salt__['sysctl.get']('hw.ncpu')
if not ncpu_data:
# We need at least one CPU to run
return 1
else:
return _number(ncpu_data)
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_nproc,
'Darwin': generic_nproc,
'FreeBSD': generic_nproc,
'OpenBSD': generic_nproc,
'AIX': _aix_nproc,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netstats():
'''
Return the network stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.netstats
'''
def linux_netstats():
'''
linux specific netstats implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
headers = ['']
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
else:
headers = comps
return ret
def freebsd_netstats():
return bsd_netstats()
def bsd_netstats():
'''
bsd specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
if line.startswith('\t\t'):
continue # Skip, too detailed
if not line.startswith('\t'):
key = line.split()[0].replace(':', '')
ret[key] = {}
else:
comps = line.split()
if comps[0].isdigit():
ret[key][' '.join(comps[1:])] = comps[0]
return ret
def sunos_netstats():
'''
sunos specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
line = line.replace('=', ' = ').split()
if len(line) > 6:
line.pop(0)
if '=' in line:
if len(line) >= 3:
if line[2].isdigit() or line[2][0] == '-':
line[2] = _number(line[2])
ret[line[0]] = line[2]
if len(line) >= 6:
if line[5].isdigit() or line[5][0] == '-':
line[5] = _number(line[5])
ret[line[3]] = line[5]
return ret
def aix_netstats():
'''
AIX specific netstats implementation
'''
ret = {}
fields = []
procn = None
proto_name = None
for line in __salt__['cmd.run']('netstat -s').splitlines():
if not line:
continue
if not re.match(r'\s', line) and ':' in line:
comps = line.split(':')
proto_name = comps[0]
ret[proto_name] = []
procn = len(ret[proto_name])
ret[proto_name].append({})
continue
else:
comps = line.split()
comps[0] = comps[0].strip()
if comps[0].isdigit():
ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])
else:
continue
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netstats,
'FreeBSD': bsd_netstats,
'OpenBSD': bsd_netstats,
'SunOS': sunos_netstats,
'AIX': aix_netstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific implementation of netdev
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
if line.find(':') < 0:
continue
comps = line.split()
# Fix lines like eth0:9999..'
comps[0] = line.split(':')[0].strip()
# Support lines both like eth0:999 and eth0: 9999
comps.insert(1, line.split(':')[1].strip().split()[0])
ret[comps[0]] = {'iface': comps[0],
'rx_bytes': _number(comps[2]),
'rx_compressed': _number(comps[8]),
'rx_drop': _number(comps[5]),
'rx_errs': _number(comps[4]),
'rx_fifo': _number(comps[6]),
'rx_frame': _number(comps[7]),
'rx_multicast': _number(comps[9]),
'rx_packets': _number(comps[3]),
'tx_bytes': _number(comps[10]),
'tx_carrier': _number(comps[16]),
'tx_colls': _number(comps[15]),
'tx_compressed': _number(comps[17]),
'tx_drop': _number(comps[13]),
'tx_errs': _number(comps[12]),
'tx_fifo': _number(comps[14]),
'tx_packets': _number(comps[11])}
return ret
def freebsd_netdev():
'''
freebsd specific implementation of netdev
'''
_dict_tree = lambda: collections.defaultdict(_dict_tree)
ret = _dict_tree()
netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()
netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]
header = netstat[0].split()
for line in netstat[1:]:
comps = line.split()
for i in range(4, 13): # The columns we want
ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])
return ret
def sunos_netdev():
'''
sunos specific implementation of netdev
'''
ret = {}
##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:
# fetch device info
netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()
# prepare data
netstat_ipv4[0] = netstat_ipv4[0].split()
netstat_ipv4[1] = netstat_ipv4[1].split()
netstat_ipv6[0] = netstat_ipv6[0].split()
netstat_ipv6[1] = netstat_ipv6[1].split()
# add data
ret[dev] = {}
for i in range(len(netstat_ipv4[0])-1):
if netstat_ipv4[0][i] == 'Name':
continue
if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]
else:
ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])
for i in range(len(netstat_ipv6[0])-1):
if netstat_ipv6[0][i] == 'Name':
continue
if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]
else:
ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])
return ret
def aix_netdev():
'''
AIX specific implementation of netdev
'''
ret = {}
fields = []
procn = None
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():
# fetch device info
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0
#en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0
netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()
# add data
ret[dev] = []
for line in netstat_ipv4:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv4'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv4'][fields[i]] = comps[i]
for line in netstat_ipv6:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv6'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv6'][fields[i]] = comps[i]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netdev,
'FreeBSD': freebsd_netdev,
'SunOS': sunos_netdev,
'AIX': aix_netdev,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def w(): # pylint: disable=C0103
'''
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
'''
def linux_w():
'''
Linux specific implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -fh').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'idle': comps[3],
'jcpu': comps[4],
'login': comps[2],
'pcpu': comps[5],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[6:])}
user_list.append(rec)
return user_list
def bsd_w():
'''
Generic BSD implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -h').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'from': comps[2],
'idle': comps[4],
'login': comps[3],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[5:])}
user_list.append(rec)
return user_list
# dict that returns a function that does the right thing per platform
get_version = {
'Darwin': bsd_w,
'FreeBSD': bsd_w,
'Linux': linux_w,
'OpenBSD': bsd_w,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def all_status():
'''
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
'''
return {'cpuinfo': cpuinfo(),
'cpustats': cpustats(),
'diskstats': diskstats(),
'diskusage': diskusage(),
'loadavg': loadavg(),
'meminfo': meminfo(),
'netdev': netdev(),
'netstats': netstats(),
'uptime': uptime(),
'vmstats': vmstats(),
'w': w()}
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
'''
cmd = __grains__['ps']
output = __salt__['cmd.run_stdout'](cmd, python_shell=True)
pids = ''
for line in output.splitlines():
if 'status.pid' in line:
continue
if re.search(sig, line):
if pids:
pids += '\n'
pids += line.split()[1]
return pids
def master(master=None, connected=True):
'''
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
master_ips = None
if master:
master_ips = salt.utils.network.host_to_ips(master)
if not master_ips:
return
master_connection_status = False
port = __salt__['config.get']('publish_port', default=4505)
connected_ips = salt.utils.network.remote_port_tcp(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
def ping_master(master):
'''
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
'''
if master is None or master == '':
return False
opts = copy.deepcopy(__opts__)
opts['master'] = master
if 'master_ip' in opts: # avoid 'master ip changed' warning
del opts['master_ip']
opts.update(salt.minion.prep_ip_port(opts))
try:
opts.update(salt.minion.resolve_dns(opts, fallback=False))
except Exception:
return False
timeout = opts.get('auth_timeout', 60)
load = {'cmd': 'ping'}
result = False
channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear')
try:
payload = channel.send(load, tries=0, timeout=timeout)
result = True
except Exception as e:
pass
if result:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
event.fire_event({'master': master}, salt.minion.master_event(type='failback'))
return result
def proxy_reconnect(proxy_name, opts=None):
'''
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
'''
if not opts:
opts = __opts__
if 'proxy' not in opts:
return False # fail
proxy_keepalive_fn = proxy_name+'.alive'
if proxy_keepalive_fn not in __proxy__:
return False # fail
is_alive = __proxy__[proxy_keepalive_fn](opts)
if not is_alive:
minion_id = opts.get('proxyid', '') or opts.get('id', '')
log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name)
__proxy__[proxy_name+'.shutdown'](opts) # safely close connection
__proxy__[proxy_name+'.init'](opts) # reopen connection
log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name)
return True # success
def time_(format='%A, %d. %B %Y %I:%M%p'):
'''
.. versionadded:: 2016.3.0
Return the current time on the minion,
formatted based on the format parameter.
Default date format: Monday, 27. July 2015 07:55AM
CLI Example:
.. code-block:: bash
salt '*' status.time
salt '*' status.time '%s'
'''
dt = datetime.datetime.today()
return dt.strftime(format)
|
saltstack/salt
|
salt/modules/status.py
|
master
|
python
|
def master(master=None, connected=True):
'''
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
master_ips = None
if master:
master_ips = salt.utils.network.host_to_ips(master)
if not master_ips:
return
master_connection_status = False
port = __salt__['config.get']('publish_port', default=4505)
connected_ips = salt.utils.network.remote_port_tcp(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1595-L1639
|
[
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n",
"def host_to_ips(host):\n '''\n Returns a list of IP addresses of a given hostname or None if not found.\n '''\n ips = []\n try:\n for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(\n host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM):\n if family == socket.AF_INET:\n ip, port = sockaddr\n elif family == socket.AF_INET6:\n ip, port, flow_info, scope_id = sockaddr\n ips.append(ip)\n if not ips:\n ips = None\n except Exception:\n ips = None\n return ips\n",
"def master_event(type, master=None):\n '''\n Centralized master event function which will return event type based on event_map\n '''\n event_map = {'connected': '__master_connected',\n 'disconnected': '__master_disconnected',\n 'failback': '__master_failback',\n 'alive': '__master_alive'}\n\n if type == 'alive' and master is not None:\n return '{0}_{1}'.format(event_map.get(type), master)\n\n return event_map.get(type, None)\n",
"def remote_port_tcp(port):\n '''\n Return a set of ip addrs the current host is connected to on given port\n '''\n ret = _remotes_on(port, 'remote_port')\n return ret\n",
"def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import logging
import fnmatch
import collections
import copy
import time
import logging
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.config
import salt.minion
import salt.utils.event
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__file__)
__virtualname__ = 'status'
__opts__ = {}
# Don't shadow built-in's.
__func_alias__ = {
'time_': 'time'
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Not all functions supported by Windows
'''
if salt.utils.platform.is_windows():
return False, 'Windows platform is not supported by this module'
return __virtualname__
def _number(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
if text.isdigit():
return int(text)
try:
return float(text)
except ValueError:
return text
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
'''
boot_secs = 0
res = __salt__['cmd.run_all']('ps -o etime= -p 1')
if res['retcode'] > 0:
raise CommandExecutionError('Unable to find boot_time for pid 1.')
bt_time = res['stdout']
days = bt_time.split('-')
hms = days[1].split(':')
boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2])
return boot_secs
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
'5-min': load_avg[2].strip(','),
'15-min': load_avg[3]}
def _aix_nproc():
'''
Return the maximun number of PROCESSES allowed per user on AIX
'''
nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split()
return _number(nprocs[1])
def procs():
'''
Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs
'''
# Get the user, pid and cmd
ret = {}
uind = 0
pind = 0
cind = 0
plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines()
guide = plines.pop(0).split()
if 'USER' in guide:
uind = guide.index('USER')
elif 'UID' in guide:
uind = guide.index('UID')
if 'PID' in guide:
pind = guide.index('PID')
if 'COMMAND' in guide:
cind = guide.index('COMMAND')
elif 'CMD' in guide:
cind = guide.index('CMD')
for line in plines:
if not line:
continue
comps = line.split()
ret[comps[pind]] = {'user': comps[uind],
'cmd': ' '.join(comps[cind:])}
return ret
def custom():
'''
Return a custom composite of status data and info for this minion,
based on the minion config file. An example config like might be::
status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ]
Where status refers to status.py, cpustats is the function
where we get our data, and custom is this function It is followed
by a list of keys that we want returned.
This function is meant to replace all_status(), which returns
anything and everything, which we probably don't want.
By default, nothing is returned. Warning: Depending on what you
include, there can be a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.custom
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
for key, val in six.iteritems(conf):
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123
for item in val:
ret[item] = vals[item]
return ret
def uptime():
'''
Return the uptime for this system.
.. versionchanged:: 2015.8.9
The uptime function was changed to return a dictionary of easy-to-read
key/value pairs containing uptime information, instead of the output
from a ``cmd.run`` call.
.. versionchanged:: 2016.11.0
Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.uptime
'''
curr_seconds = time.time()
# Get uptime in seconds
if salt.utils.platform.is_linux():
ut_path = "/proc/uptime"
if not os.path.exists(ut_path):
raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path))
with salt.utils.files.fopen(ut_path) as rfh:
seconds = int(float(rfh.read().split()[0]))
elif salt.utils.platform.is_sunos():
# note: some flavors/versions report the host uptime inside a zone
# https://support.oracle.com/epmos/faces/BugDisplay?id=15611584
res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')
if res['retcode'] > 0:
raise CommandExecutionError('The boot_time kstat was not found.')
seconds = int(curr_seconds - int(res['stdout'].split()[-1]))
elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
seconds = int(curr_seconds - int(bt_data))
elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():
# format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '')
uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])
seconds = int(curr_seconds - uptime['sec'])
elif salt.utils.platform.is_aix():
seconds = _get_boot_time_aix()
else:
return __salt__['cmd.run']('uptime')
# Setup datetime and timedelta objects
boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)
curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)
up_time = curr_time - boot_time
# Construct return information
ut_ret = {
'seconds': seconds,
'since_iso': boot_time.isoformat(),
'since_t': int(curr_seconds - seconds),
'days': up_time.days,
'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),
}
if salt.utils.path.which('who'):
who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s
ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))
return ut_ret
def loadavg():
'''
Return the load averages for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.loadavg
:raises CommandExecutionError: If the system cannot report loadaverages to Python
'''
if __grains__['kernel'] == 'AIX':
return _aix_loadavg()
try:
load_avg = os.getloadavg()
except AttributeError:
# Some UNIX-based operating systems do not have os.getloadavg()
raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')
return {'1-min': load_avg[0],
'5-min': load_avg[1],
'15-min': load_avg[2]}
def cpustats():
'''
Return the CPU stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpustats
'''
def linux_cpustats():
'''
linux specific implementation of cpustats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == 'cpu':
ret[comps[0]] = {'idle': _number(comps[4]),
'iowait': _number(comps[5]),
'irq': _number(comps[6]),
'nice': _number(comps[2]),
'softirq': _number(comps[7]),
'steal': _number(comps[8]),
'system': _number(comps[3]),
'user': _number(comps[1])}
elif comps[0] == 'intr':
ret[comps[0]] = {'total': _number(comps[1]),
'irqs': [_number(x) for x in comps[2:]]}
elif comps[0] == 'softirq':
ret[comps[0]] = {'total': _number(comps[1]),
'softirqs': [_number(x) for x in comps[2:]]}
else:
ret[comps[0]] = _number(comps[1])
return ret
def freebsd_cpustats():
'''
freebsd specific implementation of cpustats
'''
vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
vm0 = vmstat[0].split()
cpu0loc = vm0.index('cpu0')
vm1 = vmstat[1].split()
usloc = vm1.index('us')
vm2 = vmstat[2].split()
cpuctr = 0
ret = {}
for cpu in vm0[cpu0loc:]:
ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
cpuctr += 1
return ret
def sunos_cpustats():
'''
sunos specific implementation of cpustats
'''
mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
fields = mpstat[0].split()
ret = {}
for cpu in mpstat:
if cpu.startswith('CPU'):
continue
cpu = cpu.split()
ret[_number(cpu[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
return ret
def aix_cpustats():
'''
AIX specific implementation of cpustats
'''
ret = {}
ret['mpstat'] = []
procn = None
fields = []
for line in __salt__['cmd.run']('mpstat -a').splitlines():
if not line:
continue
procn = len(ret['mpstat'])
if line.startswith('System'):
comps = line.split(':')
ret['mpstat'].append({})
ret['mpstat'][procn]['system'] = {}
cpu_comps = comps[1].split()
for i in range(0, len(cpu_comps)):
cpu_vals = cpu_comps[i].split('=')
ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]
if line.startswith('cpu'):
fields = line.split()
continue
if fields:
cpustat = line.split()
ret[_number(cpustat[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])
return ret
def openbsd_cpustats():
'''
openbsd specific implementation of cpustats
'''
systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
fields = systat[3].split()
ret = {}
for cpu in systat[4:]:
cpu_line = cpu.split()
cpu_idx = cpu_line[0]
ret[cpu_idx] = {}
for idx, field in enumerate(fields[1:]):
ret[cpu_idx][field] = cpu_line[idx+1]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_cpustats,
'FreeBSD': freebsd_cpustats,
'OpenBSD': openbsd_cpustats,
'SunOS': sunos_cpustats,
'AIX': aix_cpustats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''
linux specific implementation of meminfo
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {
'value': comps[1],
}
if len(comps) > 2:
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'''
freebsd specific implementation of meminfo
'''
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
# Special handling for vm.total as it's especially important
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
def aix_meminfo():
'''
AIX specific implementation of meminfo
'''
ret = {}
ret['svmon'] = []
ret['vmstat'] = []
procn = None
fields = []
pagesize_flag = False
for line in __salt__['cmd.run']('svmon -G').splitlines():
# Note: svmon is per-system
# size inuse free pin virtual mmode
#memory 1048576 1039740 8836 285078 474993 Ded
#pg space 917504 2574
#
# work pers clnt other
#pin 248379 0 2107 34592
#in use 474993 0 564747
#
#PageSize PoolSize inuse pgsp pin virtual
#s 4 KB - 666956 2574 60726 102209
#m 64 KB - 23299 0 14022 23299
if not line:
continue
if re.match(r'\s', line):
# assume fields line
fields = line.split()
continue
if line.startswith('memory') or line.startswith('pin'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i + 1:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
continue
if line.startswith('pg space') or line.startswith('in use'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
pg_space = '{0} {1}'.format(comps[0], comps[1])
ret['svmon'][procn][pg_space] = {}
for i in range(0, len(fields)):
if len(comps) > i + 2:
ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
continue
if line.startswith('PageSize'):
fields = line.split()
pagesize_flag = False
continue
if pagesize_flag:
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
continue
for line in __salt__['cmd.run']('vmstat -v').splitlines():
# Note: vmstat is per-system
if not line:
continue
procn = len(ret['vmstat'])
ret['vmstat'].append({})
comps = line.lstrip().split(' ', 1)
ret['vmstat'][procn][comps[1]] = comps[0]
return ret
def openbsd_meminfo():
'''
openbsd specific implementation of meminfo
'''
vmstat = __salt__['cmd.run']('vmstat').splitlines()
# We're only interested in memory and page values which are printed
# as subsequent fields.
fields = ['active virtual pages', 'free list size', 'page faults',
'pages reclaimed', 'pages paged in', 'pages paged out',
'pages freed', 'pages scanned']
data = vmstat[2].split()[2:10]
ret = dict(zip(fields, data))
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_meminfo,
'FreeBSD': freebsd_meminfo,
'OpenBSD': openbsd_meminfo,
'AIX': aix_meminfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def cpuinfo():
'''
.. versionchanged:: 2016.3.2
Return the CPU info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for NetBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpuinfo
'''
def linux_cpuinfo():
'''
linux specific cpuinfo implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
if comps[0] == 'flags':
ret[comps[0]] = comps[1].split()
else:
ret[comps[0]] = comps[1].strip()
return ret
def bsd_cpuinfo():
'''
bsd specific cpuinfo implementation
'''
bsd_cmd = 'sysctl hw.model hw.ncpu'
ret = {}
if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:
sep = '='
else:
sep = ':'
for line in __salt__['cmd.run'](bsd_cmd).splitlines():
if not line:
continue
comps = line.split(sep)
comps[0] = comps[0].strip()
ret[comps[0]] = comps[1].strip()
return ret
def sunos_cpuinfo():
'''
sunos specific cpuinfo implementation
'''
ret = {}
ret['isainfo'] = {}
for line in __salt__['cmd.run']('isainfo -x').splitlines():
# Note: isainfo is per-system and not per-cpu
# Output Example:
#amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu
#i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())
ret['psrinfo'] = []
procn = None
for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():
# Output Example:
#The physical processor has 6 cores and 12 virtual processors (0-5 12-17)
# The core has 2 virtual processors (0 12)
# The core has 2 virtual processors (1 13)
# The core has 2 virtual processors (2 14)
# The core has 2 virtual processors (3 15)
# The core has 2 virtual processors (4 16)
# The core has 2 virtual processors (5 17)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#The physical processor has 6 cores and 12 virtual processors (6-11 18-23)
# The core has 2 virtual processors (6 18)
# The core has 2 virtual processors (7 19)
# The core has 2 virtual processors (8 20)
# The core has 2 virtual processors (9 21)
# The core has 2 virtual processors (10 22)
# The core has 2 virtual processors (11 23)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#
# Output Example 2:
#The physical processor has 4 virtual processors (0-3)
# x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)
# Intel(r) Atom(tm) CPU C2558 @ 2.40GHz
if not line:
continue
if line.startswith('The physical processor'):
procn = len(ret['psrinfo'])
line = line.split()
ret['psrinfo'].append({})
if 'cores' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])
ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])
elif 'virtual' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])
elif line.startswith(' ' * 6): # 3x2 space indent
ret['psrinfo'][procn]['name'] = line.strip()
elif line.startswith(' ' * 4): # 2x2 space indent
line = line.strip().split()
ret['psrinfo'][procn]['vendor'] = line[1][1:]
ret['psrinfo'][procn]['family'] = _number(line[4])
ret['psrinfo'][procn]['model'] = _number(line[6])
ret['psrinfo'][procn]['step'] = _number(line[8])
ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1])
return ret
def aix_cpuinfo():
'''
AIX specific cpuinfo implementation
'''
ret = {}
ret['prtconf'] = []
ret['lparstat'] = []
procn = None
for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#prtconf | grep -i "Processor"
#Processor Type: PowerPC_POWER7
#Processor Implementation Mode: POWER 7
#Processor Version: PV_7_Compat
#Number Of Processors: 2
#Processor Clock Speed: 3000 MHz
# Model Implementation: Multiple Processor, PCI bus
# + proc0 Processor
# + proc4 Processor
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('Processor') or line.startswith('Number'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#CPU Type: 64-bit
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('CPU'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():
# Note: lparstat is per-system and not per-cpu
# Output Example:
#Online Virtual CPUs : 2
#Maximum Virtual CPUs : 2
#Minimum Virtual CPUs : 1
#Maximum Physical CPUs in system : 32
#Active Physical CPUs in system : 32
#Active CPUs in Pool : 32
#Shared Physical CPUs in system : 32
#Physical CPU Percentage : 25.00%
#Desired Virtual CPUs : 2
if not line:
continue
procn = len(ret['lparstat'])
ret['lparstat'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['lparstat'][procn][comps[0]] = comps[1]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_cpuinfo,
'FreeBSD': bsd_cpuinfo,
'NetBSD': bsd_cpuinfo,
'OpenBSD': bsd_cpuinfo,
'SunOS': sunos_cpuinfo,
'AIX': aix_cpuinfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific implementation of diskstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[2]] = {
'major': _number(comps[0]),
'minor': _number(comps[1]),
'device': _number(comps[2]),
'reads_issued': _number(comps[3]),
'reads_merged': _number(comps[4]),
'sectors_read': _number(comps[5]),
'ms_spent_reading': _number(comps[6]),
'writes_completed': _number(comps[7]),
'writes_merged': _number(comps[8]),
'sectors_written': _number(comps[9]),
'ms_spent_writing': _number(comps[10]),
'io_in_progress': _number(comps[11]),
'ms_spent_in_io': _number(comps[12]),
'weighted_ms_spent_in_io': _number(comps[13])
}
return ret
def generic_diskstats():
'''
generic implementation of diskstats
note: freebsd and sunos
'''
ret = {}
iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
header = iostat[1]
for line in iostat[2:]:
comps = line.split()
ret[comps[0]] = {}
for metric, value in zip(header.split()[1:], comps[1:]):
ret[comps[0]][metric] = _number(value)
return ret
def aix_diskstats():
'''
AIX specific implementation of diskstats
'''
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
for line in __salt__['cmd.run']('iostat -dDV').splitlines():
# Note: iostat -dDV is per-system
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk0 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.8 0.0 0.0 0.8
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 2.5 0.3 12.4 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.3 0.2 0.7 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.3 0.0 5.3 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#have new disk
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()
ret[disk_name] = []
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
else:
comps = line.split()
for i in range(0, len(fields)):
if len(comps) > i:
ret[disk_name][procn][disk_mode][fields[i]] = comps[i]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_diskstats,
'FreeBSD': generic_diskstats,
'SunOS': generic_diskstats,
'AIX': aix_diskstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskusage(*args):
'''
Return the disk usage for this minion
Usage::
salt '*' status.diskusage [paths and/or filesystem types]
CLI Example:
.. code-block:: bash
salt '*' status.diskusage # usage for all filesystems
salt '*' status.diskusage / /tmp # usage for / and /tmp
salt '*' status.diskusage ext? # usage for ext[234] filesystems
salt '*' status.diskusage / ext? # usage for / and all ext filesystems
'''
selected = set()
fstypes = set()
if not args:
# select all filesystems
fstypes.add('*')
else:
for arg in args:
if arg.startswith('/'):
# select path
selected.add(arg)
else:
# select fstype
fstypes.add(arg)
if fstypes:
# determine which mount points host the specified fstypes
regex = re.compile(
'|'.join(
fnmatch.translate(fstype).format('(%s)') for fstype in fstypes
)
)
# ifile source of data varies with OS, otherwise all the same
if __grains__['kernel'] == 'Linux':
try:
with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:
ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()
except OSError:
return {}
elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):
ifile = __salt__['cmd.run']('mount -p').splitlines()
else:
raise CommandExecutionError('status.diskusage not yet supported on this platform')
for line in ifile:
comps = line.split()
if __grains__['kernel'] == 'SunOS':
if len(comps) >= 4:
mntpt = comps[2]
fstype = comps[3]
if regex.match(fstype):
selected.add(mntpt)
else:
if len(comps) >= 3:
mntpt = comps[1]
fstype = comps[2]
if regex.match(fstype):
selected.add(mntpt)
# query the filesystems disk usage
ret = {}
for path in selected:
fsstats = os.statvfs(path)
blksz = fsstats.f_bsize
available = fsstats.f_bavail * blksz
total = fsstats.f_blocks * blksz
ret[path] = {"available": available, "total": total}
return ret
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specific implementation of vmstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[0]] = _number(comps[1])
return ret
def generic_vmstats():
'''
generic implementation of vmstats
note: works on FreeBSD, SunOS and OpenBSD (possibly others)
'''
ret = {}
for line in __salt__['cmd.run']('vmstat -s').splitlines():
comps = line.split()
if comps[0].isdigit():
ret[' '.join(comps[1:])] = _number(comps[0].strip())
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_vmstats,
'FreeBSD': generic_vmstats,
'OpenBSD': generic_vmstats,
'SunOS': generic_vmstats,
'AIX': generic_vmstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def nproc():
'''
Return the number of processing units available on this system
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for Darwin, FreeBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.nproc
'''
def linux_nproc():
'''
linux specific implementation of nproc
'''
try:
return _number(__salt__['cmd.run']('nproc').strip())
except ValueError:
return 0
def generic_nproc():
'''
generic implementation of nproc
'''
ncpu_data = __salt__['sysctl.get']('hw.ncpu')
if not ncpu_data:
# We need at least one CPU to run
return 1
else:
return _number(ncpu_data)
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_nproc,
'Darwin': generic_nproc,
'FreeBSD': generic_nproc,
'OpenBSD': generic_nproc,
'AIX': _aix_nproc,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netstats():
'''
Return the network stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.netstats
'''
def linux_netstats():
'''
linux specific netstats implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
headers = ['']
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
else:
headers = comps
return ret
def freebsd_netstats():
return bsd_netstats()
def bsd_netstats():
'''
bsd specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
if line.startswith('\t\t'):
continue # Skip, too detailed
if not line.startswith('\t'):
key = line.split()[0].replace(':', '')
ret[key] = {}
else:
comps = line.split()
if comps[0].isdigit():
ret[key][' '.join(comps[1:])] = comps[0]
return ret
def sunos_netstats():
'''
sunos specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
line = line.replace('=', ' = ').split()
if len(line) > 6:
line.pop(0)
if '=' in line:
if len(line) >= 3:
if line[2].isdigit() or line[2][0] == '-':
line[2] = _number(line[2])
ret[line[0]] = line[2]
if len(line) >= 6:
if line[5].isdigit() or line[5][0] == '-':
line[5] = _number(line[5])
ret[line[3]] = line[5]
return ret
def aix_netstats():
'''
AIX specific netstats implementation
'''
ret = {}
fields = []
procn = None
proto_name = None
for line in __salt__['cmd.run']('netstat -s').splitlines():
if not line:
continue
if not re.match(r'\s', line) and ':' in line:
comps = line.split(':')
proto_name = comps[0]
ret[proto_name] = []
procn = len(ret[proto_name])
ret[proto_name].append({})
continue
else:
comps = line.split()
comps[0] = comps[0].strip()
if comps[0].isdigit():
ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])
else:
continue
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netstats,
'FreeBSD': bsd_netstats,
'OpenBSD': bsd_netstats,
'SunOS': sunos_netstats,
'AIX': aix_netstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific implementation of netdev
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
if line.find(':') < 0:
continue
comps = line.split()
# Fix lines like eth0:9999..'
comps[0] = line.split(':')[0].strip()
# Support lines both like eth0:999 and eth0: 9999
comps.insert(1, line.split(':')[1].strip().split()[0])
ret[comps[0]] = {'iface': comps[0],
'rx_bytes': _number(comps[2]),
'rx_compressed': _number(comps[8]),
'rx_drop': _number(comps[5]),
'rx_errs': _number(comps[4]),
'rx_fifo': _number(comps[6]),
'rx_frame': _number(comps[7]),
'rx_multicast': _number(comps[9]),
'rx_packets': _number(comps[3]),
'tx_bytes': _number(comps[10]),
'tx_carrier': _number(comps[16]),
'tx_colls': _number(comps[15]),
'tx_compressed': _number(comps[17]),
'tx_drop': _number(comps[13]),
'tx_errs': _number(comps[12]),
'tx_fifo': _number(comps[14]),
'tx_packets': _number(comps[11])}
return ret
def freebsd_netdev():
'''
freebsd specific implementation of netdev
'''
_dict_tree = lambda: collections.defaultdict(_dict_tree)
ret = _dict_tree()
netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()
netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]
header = netstat[0].split()
for line in netstat[1:]:
comps = line.split()
for i in range(4, 13): # The columns we want
ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])
return ret
def sunos_netdev():
'''
sunos specific implementation of netdev
'''
ret = {}
##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:
# fetch device info
netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()
# prepare data
netstat_ipv4[0] = netstat_ipv4[0].split()
netstat_ipv4[1] = netstat_ipv4[1].split()
netstat_ipv6[0] = netstat_ipv6[0].split()
netstat_ipv6[1] = netstat_ipv6[1].split()
# add data
ret[dev] = {}
for i in range(len(netstat_ipv4[0])-1):
if netstat_ipv4[0][i] == 'Name':
continue
if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]
else:
ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])
for i in range(len(netstat_ipv6[0])-1):
if netstat_ipv6[0][i] == 'Name':
continue
if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]
else:
ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])
return ret
def aix_netdev():
'''
AIX specific implementation of netdev
'''
ret = {}
fields = []
procn = None
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():
# fetch device info
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0
#en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0
netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()
# add data
ret[dev] = []
for line in netstat_ipv4:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv4'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv4'][fields[i]] = comps[i]
for line in netstat_ipv6:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv6'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv6'][fields[i]] = comps[i]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netdev,
'FreeBSD': freebsd_netdev,
'SunOS': sunos_netdev,
'AIX': aix_netdev,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def w(): # pylint: disable=C0103
'''
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
'''
def linux_w():
'''
Linux specific implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -fh').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'idle': comps[3],
'jcpu': comps[4],
'login': comps[2],
'pcpu': comps[5],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[6:])}
user_list.append(rec)
return user_list
def bsd_w():
'''
Generic BSD implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -h').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'from': comps[2],
'idle': comps[4],
'login': comps[3],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[5:])}
user_list.append(rec)
return user_list
# dict that returns a function that does the right thing per platform
get_version = {
'Darwin': bsd_w,
'FreeBSD': bsd_w,
'Linux': linux_w,
'OpenBSD': bsd_w,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def all_status():
'''
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
'''
return {'cpuinfo': cpuinfo(),
'cpustats': cpustats(),
'diskstats': diskstats(),
'diskusage': diskusage(),
'loadavg': loadavg(),
'meminfo': meminfo(),
'netdev': netdev(),
'netstats': netstats(),
'uptime': uptime(),
'vmstats': vmstats(),
'w': w()}
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
'''
cmd = __grains__['ps']
output = __salt__['cmd.run_stdout'](cmd, python_shell=True)
pids = ''
for line in output.splitlines():
if 'status.pid' in line:
continue
if re.search(sig, line):
if pids:
pids += '\n'
pids += line.split()[1]
return pids
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
'''
linux specific implementation of version
'''
try:
with salt.utils.files.fopen('/proc/version', 'r') as fp_:
return salt.utils.stringutils.to_unicode(fp_.read()).strip()
except IOError:
return {}
def bsd_version():
'''
bsd specific implementation of version
'''
return __salt__['cmd.run']('sysctl -n kern.version')
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_version,
'FreeBSD': bsd_version,
'OpenBSD': bsd_version,
'AIX': lambda: __salt__['cmd.run']('oslevel -s'),
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def ping_master(master):
'''
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
'''
if master is None or master == '':
return False
opts = copy.deepcopy(__opts__)
opts['master'] = master
if 'master_ip' in opts: # avoid 'master ip changed' warning
del opts['master_ip']
opts.update(salt.minion.prep_ip_port(opts))
try:
opts.update(salt.minion.resolve_dns(opts, fallback=False))
except Exception:
return False
timeout = opts.get('auth_timeout', 60)
load = {'cmd': 'ping'}
result = False
channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear')
try:
payload = channel.send(load, tries=0, timeout=timeout)
result = True
except Exception as e:
pass
if result:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
event.fire_event({'master': master}, salt.minion.master_event(type='failback'))
return result
def proxy_reconnect(proxy_name, opts=None):
'''
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
'''
if not opts:
opts = __opts__
if 'proxy' not in opts:
return False # fail
proxy_keepalive_fn = proxy_name+'.alive'
if proxy_keepalive_fn not in __proxy__:
return False # fail
is_alive = __proxy__[proxy_keepalive_fn](opts)
if not is_alive:
minion_id = opts.get('proxyid', '') or opts.get('id', '')
log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name)
__proxy__[proxy_name+'.shutdown'](opts) # safely close connection
__proxy__[proxy_name+'.init'](opts) # reopen connection
log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name)
return True # success
def time_(format='%A, %d. %B %Y %I:%M%p'):
'''
.. versionadded:: 2016.3.0
Return the current time on the minion,
formatted based on the format parameter.
Default date format: Monday, 27. July 2015 07:55AM
CLI Example:
.. code-block:: bash
salt '*' status.time
salt '*' status.time '%s'
'''
dt = datetime.datetime.today()
return dt.strftime(format)
|
saltstack/salt
|
salt/modules/status.py
|
ping_master
|
python
|
def ping_master(master):
'''
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
'''
if master is None or master == '':
return False
opts = copy.deepcopy(__opts__)
opts['master'] = master
if 'master_ip' in opts: # avoid 'master ip changed' warning
del opts['master_ip']
opts.update(salt.minion.prep_ip_port(opts))
try:
opts.update(salt.minion.resolve_dns(opts, fallback=False))
except Exception:
return False
timeout = opts.get('auth_timeout', 60)
load = {'cmd': 'ping'}
result = False
channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear')
try:
payload = channel.send(load, tries=0, timeout=timeout)
result = True
except Exception as e:
pass
if result:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
event.fire_event({'master': master}, salt.minion.master_event(type='failback'))
return result
|
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1642-L1683
|
[
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n",
"def resolve_dns(opts, fallback=True):\n '''\n Resolves the master_ip and master_uri options\n '''\n ret = {}\n check_dns = True\n if (opts.get('file_client', 'remote') == 'local' and\n not opts.get('use_master_when_local', False)):\n check_dns = False\n # Since salt.log is imported below, salt.utils.network needs to be imported here as well\n import salt.utils.network\n\n if check_dns is True:\n try:\n if opts['master'] == '':\n raise SaltSystemExit\n ret['master_ip'] = salt.utils.network.dns_check(\n opts['master'],\n int(opts['master_port']),\n True,\n opts['ipv6'],\n attempt_connect=False)\n except SaltClientError:\n retry_dns_count = opts.get('retry_dns_count', None)\n if opts['retry_dns']:\n while True:\n if retry_dns_count is not None:\n if retry_dns_count == 0:\n raise SaltMasterUnresolvableError\n retry_dns_count -= 1\n import salt.log\n msg = ('Master hostname: \\'{0}\\' not found or not responsive. '\n 'Retrying in {1} seconds').format(opts['master'], opts['retry_dns'])\n if salt.log.setup.is_console_configured():\n log.error(msg)\n else:\n print('WARNING: {0}'.format(msg))\n time.sleep(opts['retry_dns'])\n try:\n ret['master_ip'] = salt.utils.network.dns_check(\n opts['master'],\n int(opts['master_port']),\n True,\n opts['ipv6'],\n attempt_connect=False)\n break\n except SaltClientError:\n pass\n else:\n if fallback:\n ret['master_ip'] = '127.0.0.1'\n else:\n raise\n except SaltSystemExit:\n unknown_str = 'unknown address'\n master = opts.get('master', unknown_str)\n if master == '':\n master = unknown_str\n if opts.get('__role') == 'syndic':\n err = 'Master address: \\'{0}\\' could not be resolved. Invalid or unresolveable address. ' \\\n 'Set \\'syndic_master\\' value in minion config.'.format(master)\n else:\n err = 'Master address: \\'{0}\\' could not be resolved. Invalid or unresolveable address. ' \\\n 'Set \\'master\\' value in minion config.'.format(master)\n log.error(err)\n raise SaltSystemExit(code=42, msg=err)\n else:\n ret['master_ip'] = '127.0.0.1'\n\n if 'master_ip' in ret and 'master_ip' in opts:\n if ret['master_ip'] != opts['master_ip']:\n log.warning(\n 'Master ip address changed from %s to %s',\n opts['master_ip'], ret['master_ip']\n )\n if opts['source_interface_name']:\n log.trace('Custom source interface required: %s', opts['source_interface_name'])\n interfaces = salt.utils.network.interfaces()\n log.trace('The following interfaces are available on this Minion:')\n log.trace(interfaces)\n if opts['source_interface_name'] in interfaces:\n if interfaces[opts['source_interface_name']]['up']:\n addrs = interfaces[opts['source_interface_name']]['inet'] if not opts['ipv6'] else\\\n interfaces[opts['source_interface_name']]['inet6']\n ret['source_ip'] = addrs[0]['address']\n log.debug('Using %s as source IP address', ret['source_ip'])\n else:\n log.warning('The interface %s is down so it cannot be used as source to connect to the Master',\n opts['source_interface_name'])\n else:\n log.warning('%s is not a valid interface. Ignoring.', opts['source_interface_name'])\n elif opts['source_address']:\n ret['source_ip'] = salt.utils.network.dns_check(\n opts['source_address'],\n int(opts['source_ret_port']),\n True,\n opts['ipv6'],\n attempt_connect=False)\n log.debug('Using %s as source IP address', ret['source_ip'])\n if opts['source_ret_port']:\n ret['source_ret_port'] = int(opts['source_ret_port'])\n log.debug('Using %d as source port for the ret server', ret['source_ret_port'])\n if opts['source_publish_port']:\n ret['source_publish_port'] = int(opts['source_publish_port'])\n log.debug('Using %d as source port for the master pub', ret['source_publish_port'])\n ret['master_uri'] = 'tcp://{ip}:{port}'.format(\n ip=ret['master_ip'], port=opts['master_port'])\n log.debug('Master URI: %s', ret['master_uri'])\n\n return ret\n",
"def prep_ip_port(opts):\n '''\n parse host:port values from opts['master'] and return valid:\n master: ip address or hostname as a string\n master_port: (optional) master returner port as integer\n\n e.g.:\n - master: 'localhost:1234' -> {'master': 'localhost', 'master_port': 1234}\n - master: '127.0.0.1:1234' -> {'master': '127.0.0.1', 'master_port' :1234}\n - master: '[::1]:1234' -> {'master': '::1', 'master_port': 1234}\n - master: 'fe80::a00:27ff:fedc:ba98' -> {'master': 'fe80::a00:27ff:fedc:ba98'}\n '''\n ret = {}\n # Use given master IP if \"ip_only\" is set or if master_ip is an ipv6 address without\n # a port specified. The is_ipv6 check returns False if brackets are used in the IP\n # definition such as master: '[::1]:1234'.\n if opts['master_uri_format'] == 'ip_only':\n ret['master'] = ipaddress.ip_address(opts['master'])\n else:\n host, port = parse_host_port(opts['master'])\n ret = {'master': host}\n if port:\n ret.update({'master_port': port})\n\n return ret\n",
"def master_event(type, master=None):\n '''\n Centralized master event function which will return event type based on event_map\n '''\n event_map = {'connected': '__master_connected',\n 'disconnected': '__master_disconnected',\n 'failback': '__master_failback',\n 'alive': '__master_alive'}\n\n if type == 'alive' and master is not None:\n return '{0}_{1}'.format(event_map.get(type), master)\n\n return event_map.get(type, None)\n",
"def factory(opts, **kwargs):\n # All Sync interfaces are just wrappers around the Async ones\n sync = SyncWrapper(AsyncReqChannel.factory, (opts,), kwargs)\n return sync\n",
"def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import logging
import fnmatch
import collections
import copy
import time
import logging
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.config
import salt.minion
import salt.utils.event
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__file__)
__virtualname__ = 'status'
__opts__ = {}
# Don't shadow built-in's.
__func_alias__ = {
'time_': 'time'
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Not all functions supported by Windows
'''
if salt.utils.platform.is_windows():
return False, 'Windows platform is not supported by this module'
return __virtualname__
def _number(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
if text.isdigit():
return int(text)
try:
return float(text)
except ValueError:
return text
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
'''
boot_secs = 0
res = __salt__['cmd.run_all']('ps -o etime= -p 1')
if res['retcode'] > 0:
raise CommandExecutionError('Unable to find boot_time for pid 1.')
bt_time = res['stdout']
days = bt_time.split('-')
hms = days[1].split(':')
boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2])
return boot_secs
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
'5-min': load_avg[2].strip(','),
'15-min': load_avg[3]}
def _aix_nproc():
'''
Return the maximun number of PROCESSES allowed per user on AIX
'''
nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split()
return _number(nprocs[1])
def procs():
'''
Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs
'''
# Get the user, pid and cmd
ret = {}
uind = 0
pind = 0
cind = 0
plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines()
guide = plines.pop(0).split()
if 'USER' in guide:
uind = guide.index('USER')
elif 'UID' in guide:
uind = guide.index('UID')
if 'PID' in guide:
pind = guide.index('PID')
if 'COMMAND' in guide:
cind = guide.index('COMMAND')
elif 'CMD' in guide:
cind = guide.index('CMD')
for line in plines:
if not line:
continue
comps = line.split()
ret[comps[pind]] = {'user': comps[uind],
'cmd': ' '.join(comps[cind:])}
return ret
def custom():
'''
Return a custom composite of status data and info for this minion,
based on the minion config file. An example config like might be::
status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ]
Where status refers to status.py, cpustats is the function
where we get our data, and custom is this function It is followed
by a list of keys that we want returned.
This function is meant to replace all_status(), which returns
anything and everything, which we probably don't want.
By default, nothing is returned. Warning: Depending on what you
include, there can be a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.custom
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
for key, val in six.iteritems(conf):
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123
for item in val:
ret[item] = vals[item]
return ret
def uptime():
'''
Return the uptime for this system.
.. versionchanged:: 2015.8.9
The uptime function was changed to return a dictionary of easy-to-read
key/value pairs containing uptime information, instead of the output
from a ``cmd.run`` call.
.. versionchanged:: 2016.11.0
Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.uptime
'''
curr_seconds = time.time()
# Get uptime in seconds
if salt.utils.platform.is_linux():
ut_path = "/proc/uptime"
if not os.path.exists(ut_path):
raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path))
with salt.utils.files.fopen(ut_path) as rfh:
seconds = int(float(rfh.read().split()[0]))
elif salt.utils.platform.is_sunos():
# note: some flavors/versions report the host uptime inside a zone
# https://support.oracle.com/epmos/faces/BugDisplay?id=15611584
res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')
if res['retcode'] > 0:
raise CommandExecutionError('The boot_time kstat was not found.')
seconds = int(curr_seconds - int(res['stdout'].split()[-1]))
elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
seconds = int(curr_seconds - int(bt_data))
elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():
# format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '')
uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])
seconds = int(curr_seconds - uptime['sec'])
elif salt.utils.platform.is_aix():
seconds = _get_boot_time_aix()
else:
return __salt__['cmd.run']('uptime')
# Setup datetime and timedelta objects
boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)
curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)
up_time = curr_time - boot_time
# Construct return information
ut_ret = {
'seconds': seconds,
'since_iso': boot_time.isoformat(),
'since_t': int(curr_seconds - seconds),
'days': up_time.days,
'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),
}
if salt.utils.path.which('who'):
who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s
ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))
return ut_ret
def loadavg():
'''
Return the load averages for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.loadavg
:raises CommandExecutionError: If the system cannot report loadaverages to Python
'''
if __grains__['kernel'] == 'AIX':
return _aix_loadavg()
try:
load_avg = os.getloadavg()
except AttributeError:
# Some UNIX-based operating systems do not have os.getloadavg()
raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')
return {'1-min': load_avg[0],
'5-min': load_avg[1],
'15-min': load_avg[2]}
def cpustats():
'''
Return the CPU stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpustats
'''
def linux_cpustats():
'''
linux specific implementation of cpustats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == 'cpu':
ret[comps[0]] = {'idle': _number(comps[4]),
'iowait': _number(comps[5]),
'irq': _number(comps[6]),
'nice': _number(comps[2]),
'softirq': _number(comps[7]),
'steal': _number(comps[8]),
'system': _number(comps[3]),
'user': _number(comps[1])}
elif comps[0] == 'intr':
ret[comps[0]] = {'total': _number(comps[1]),
'irqs': [_number(x) for x in comps[2:]]}
elif comps[0] == 'softirq':
ret[comps[0]] = {'total': _number(comps[1]),
'softirqs': [_number(x) for x in comps[2:]]}
else:
ret[comps[0]] = _number(comps[1])
return ret
def freebsd_cpustats():
'''
freebsd specific implementation of cpustats
'''
vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
vm0 = vmstat[0].split()
cpu0loc = vm0.index('cpu0')
vm1 = vmstat[1].split()
usloc = vm1.index('us')
vm2 = vmstat[2].split()
cpuctr = 0
ret = {}
for cpu in vm0[cpu0loc:]:
ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
cpuctr += 1
return ret
def sunos_cpustats():
'''
sunos specific implementation of cpustats
'''
mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
fields = mpstat[0].split()
ret = {}
for cpu in mpstat:
if cpu.startswith('CPU'):
continue
cpu = cpu.split()
ret[_number(cpu[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
return ret
def aix_cpustats():
'''
AIX specific implementation of cpustats
'''
ret = {}
ret['mpstat'] = []
procn = None
fields = []
for line in __salt__['cmd.run']('mpstat -a').splitlines():
if not line:
continue
procn = len(ret['mpstat'])
if line.startswith('System'):
comps = line.split(':')
ret['mpstat'].append({})
ret['mpstat'][procn]['system'] = {}
cpu_comps = comps[1].split()
for i in range(0, len(cpu_comps)):
cpu_vals = cpu_comps[i].split('=')
ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]
if line.startswith('cpu'):
fields = line.split()
continue
if fields:
cpustat = line.split()
ret[_number(cpustat[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])
return ret
def openbsd_cpustats():
'''
openbsd specific implementation of cpustats
'''
systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
fields = systat[3].split()
ret = {}
for cpu in systat[4:]:
cpu_line = cpu.split()
cpu_idx = cpu_line[0]
ret[cpu_idx] = {}
for idx, field in enumerate(fields[1:]):
ret[cpu_idx][field] = cpu_line[idx+1]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_cpustats,
'FreeBSD': freebsd_cpustats,
'OpenBSD': openbsd_cpustats,
'SunOS': sunos_cpustats,
'AIX': aix_cpustats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''
linux specific implementation of meminfo
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {
'value': comps[1],
}
if len(comps) > 2:
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'''
freebsd specific implementation of meminfo
'''
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
# Special handling for vm.total as it's especially important
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
def aix_meminfo():
'''
AIX specific implementation of meminfo
'''
ret = {}
ret['svmon'] = []
ret['vmstat'] = []
procn = None
fields = []
pagesize_flag = False
for line in __salt__['cmd.run']('svmon -G').splitlines():
# Note: svmon is per-system
# size inuse free pin virtual mmode
#memory 1048576 1039740 8836 285078 474993 Ded
#pg space 917504 2574
#
# work pers clnt other
#pin 248379 0 2107 34592
#in use 474993 0 564747
#
#PageSize PoolSize inuse pgsp pin virtual
#s 4 KB - 666956 2574 60726 102209
#m 64 KB - 23299 0 14022 23299
if not line:
continue
if re.match(r'\s', line):
# assume fields line
fields = line.split()
continue
if line.startswith('memory') or line.startswith('pin'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i + 1:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
continue
if line.startswith('pg space') or line.startswith('in use'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
pg_space = '{0} {1}'.format(comps[0], comps[1])
ret['svmon'][procn][pg_space] = {}
for i in range(0, len(fields)):
if len(comps) > i + 2:
ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
continue
if line.startswith('PageSize'):
fields = line.split()
pagesize_flag = False
continue
if pagesize_flag:
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
continue
for line in __salt__['cmd.run']('vmstat -v').splitlines():
# Note: vmstat is per-system
if not line:
continue
procn = len(ret['vmstat'])
ret['vmstat'].append({})
comps = line.lstrip().split(' ', 1)
ret['vmstat'][procn][comps[1]] = comps[0]
return ret
def openbsd_meminfo():
'''
openbsd specific implementation of meminfo
'''
vmstat = __salt__['cmd.run']('vmstat').splitlines()
# We're only interested in memory and page values which are printed
# as subsequent fields.
fields = ['active virtual pages', 'free list size', 'page faults',
'pages reclaimed', 'pages paged in', 'pages paged out',
'pages freed', 'pages scanned']
data = vmstat[2].split()[2:10]
ret = dict(zip(fields, data))
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_meminfo,
'FreeBSD': freebsd_meminfo,
'OpenBSD': openbsd_meminfo,
'AIX': aix_meminfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def cpuinfo():
'''
.. versionchanged:: 2016.3.2
Return the CPU info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for NetBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpuinfo
'''
def linux_cpuinfo():
'''
linux specific cpuinfo implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
if comps[0] == 'flags':
ret[comps[0]] = comps[1].split()
else:
ret[comps[0]] = comps[1].strip()
return ret
def bsd_cpuinfo():
'''
bsd specific cpuinfo implementation
'''
bsd_cmd = 'sysctl hw.model hw.ncpu'
ret = {}
if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:
sep = '='
else:
sep = ':'
for line in __salt__['cmd.run'](bsd_cmd).splitlines():
if not line:
continue
comps = line.split(sep)
comps[0] = comps[0].strip()
ret[comps[0]] = comps[1].strip()
return ret
def sunos_cpuinfo():
'''
sunos specific cpuinfo implementation
'''
ret = {}
ret['isainfo'] = {}
for line in __salt__['cmd.run']('isainfo -x').splitlines():
# Note: isainfo is per-system and not per-cpu
# Output Example:
#amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu
#i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())
ret['psrinfo'] = []
procn = None
for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():
# Output Example:
#The physical processor has 6 cores and 12 virtual processors (0-5 12-17)
# The core has 2 virtual processors (0 12)
# The core has 2 virtual processors (1 13)
# The core has 2 virtual processors (2 14)
# The core has 2 virtual processors (3 15)
# The core has 2 virtual processors (4 16)
# The core has 2 virtual processors (5 17)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#The physical processor has 6 cores and 12 virtual processors (6-11 18-23)
# The core has 2 virtual processors (6 18)
# The core has 2 virtual processors (7 19)
# The core has 2 virtual processors (8 20)
# The core has 2 virtual processors (9 21)
# The core has 2 virtual processors (10 22)
# The core has 2 virtual processors (11 23)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#
# Output Example 2:
#The physical processor has 4 virtual processors (0-3)
# x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)
# Intel(r) Atom(tm) CPU C2558 @ 2.40GHz
if not line:
continue
if line.startswith('The physical processor'):
procn = len(ret['psrinfo'])
line = line.split()
ret['psrinfo'].append({})
if 'cores' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])
ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])
elif 'virtual' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])
elif line.startswith(' ' * 6): # 3x2 space indent
ret['psrinfo'][procn]['name'] = line.strip()
elif line.startswith(' ' * 4): # 2x2 space indent
line = line.strip().split()
ret['psrinfo'][procn]['vendor'] = line[1][1:]
ret['psrinfo'][procn]['family'] = _number(line[4])
ret['psrinfo'][procn]['model'] = _number(line[6])
ret['psrinfo'][procn]['step'] = _number(line[8])
ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1])
return ret
def aix_cpuinfo():
'''
AIX specific cpuinfo implementation
'''
ret = {}
ret['prtconf'] = []
ret['lparstat'] = []
procn = None
for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#prtconf | grep -i "Processor"
#Processor Type: PowerPC_POWER7
#Processor Implementation Mode: POWER 7
#Processor Version: PV_7_Compat
#Number Of Processors: 2
#Processor Clock Speed: 3000 MHz
# Model Implementation: Multiple Processor, PCI bus
# + proc0 Processor
# + proc4 Processor
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('Processor') or line.startswith('Number'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#CPU Type: 64-bit
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('CPU'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():
# Note: lparstat is per-system and not per-cpu
# Output Example:
#Online Virtual CPUs : 2
#Maximum Virtual CPUs : 2
#Minimum Virtual CPUs : 1
#Maximum Physical CPUs in system : 32
#Active Physical CPUs in system : 32
#Active CPUs in Pool : 32
#Shared Physical CPUs in system : 32
#Physical CPU Percentage : 25.00%
#Desired Virtual CPUs : 2
if not line:
continue
procn = len(ret['lparstat'])
ret['lparstat'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['lparstat'][procn][comps[0]] = comps[1]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_cpuinfo,
'FreeBSD': bsd_cpuinfo,
'NetBSD': bsd_cpuinfo,
'OpenBSD': bsd_cpuinfo,
'SunOS': sunos_cpuinfo,
'AIX': aix_cpuinfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific implementation of diskstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[2]] = {
'major': _number(comps[0]),
'minor': _number(comps[1]),
'device': _number(comps[2]),
'reads_issued': _number(comps[3]),
'reads_merged': _number(comps[4]),
'sectors_read': _number(comps[5]),
'ms_spent_reading': _number(comps[6]),
'writes_completed': _number(comps[7]),
'writes_merged': _number(comps[8]),
'sectors_written': _number(comps[9]),
'ms_spent_writing': _number(comps[10]),
'io_in_progress': _number(comps[11]),
'ms_spent_in_io': _number(comps[12]),
'weighted_ms_spent_in_io': _number(comps[13])
}
return ret
def generic_diskstats():
'''
generic implementation of diskstats
note: freebsd and sunos
'''
ret = {}
iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
header = iostat[1]
for line in iostat[2:]:
comps = line.split()
ret[comps[0]] = {}
for metric, value in zip(header.split()[1:], comps[1:]):
ret[comps[0]][metric] = _number(value)
return ret
def aix_diskstats():
'''
AIX specific implementation of diskstats
'''
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
for line in __salt__['cmd.run']('iostat -dDV').splitlines():
# Note: iostat -dDV is per-system
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk0 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.8 0.0 0.0 0.8
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 2.5 0.3 12.4 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.3 0.2 0.7 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.3 0.0 5.3 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#have new disk
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()
ret[disk_name] = []
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
else:
comps = line.split()
for i in range(0, len(fields)):
if len(comps) > i:
ret[disk_name][procn][disk_mode][fields[i]] = comps[i]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_diskstats,
'FreeBSD': generic_diskstats,
'SunOS': generic_diskstats,
'AIX': aix_diskstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskusage(*args):
'''
Return the disk usage for this minion
Usage::
salt '*' status.diskusage [paths and/or filesystem types]
CLI Example:
.. code-block:: bash
salt '*' status.diskusage # usage for all filesystems
salt '*' status.diskusage / /tmp # usage for / and /tmp
salt '*' status.diskusage ext? # usage for ext[234] filesystems
salt '*' status.diskusage / ext? # usage for / and all ext filesystems
'''
selected = set()
fstypes = set()
if not args:
# select all filesystems
fstypes.add('*')
else:
for arg in args:
if arg.startswith('/'):
# select path
selected.add(arg)
else:
# select fstype
fstypes.add(arg)
if fstypes:
# determine which mount points host the specified fstypes
regex = re.compile(
'|'.join(
fnmatch.translate(fstype).format('(%s)') for fstype in fstypes
)
)
# ifile source of data varies with OS, otherwise all the same
if __grains__['kernel'] == 'Linux':
try:
with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:
ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()
except OSError:
return {}
elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):
ifile = __salt__['cmd.run']('mount -p').splitlines()
else:
raise CommandExecutionError('status.diskusage not yet supported on this platform')
for line in ifile:
comps = line.split()
if __grains__['kernel'] == 'SunOS':
if len(comps) >= 4:
mntpt = comps[2]
fstype = comps[3]
if regex.match(fstype):
selected.add(mntpt)
else:
if len(comps) >= 3:
mntpt = comps[1]
fstype = comps[2]
if regex.match(fstype):
selected.add(mntpt)
# query the filesystems disk usage
ret = {}
for path in selected:
fsstats = os.statvfs(path)
blksz = fsstats.f_bsize
available = fsstats.f_bavail * blksz
total = fsstats.f_blocks * blksz
ret[path] = {"available": available, "total": total}
return ret
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specific implementation of vmstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[0]] = _number(comps[1])
return ret
def generic_vmstats():
'''
generic implementation of vmstats
note: works on FreeBSD, SunOS and OpenBSD (possibly others)
'''
ret = {}
for line in __salt__['cmd.run']('vmstat -s').splitlines():
comps = line.split()
if comps[0].isdigit():
ret[' '.join(comps[1:])] = _number(comps[0].strip())
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_vmstats,
'FreeBSD': generic_vmstats,
'OpenBSD': generic_vmstats,
'SunOS': generic_vmstats,
'AIX': generic_vmstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def nproc():
'''
Return the number of processing units available on this system
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for Darwin, FreeBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.nproc
'''
def linux_nproc():
'''
linux specific implementation of nproc
'''
try:
return _number(__salt__['cmd.run']('nproc').strip())
except ValueError:
return 0
def generic_nproc():
'''
generic implementation of nproc
'''
ncpu_data = __salt__['sysctl.get']('hw.ncpu')
if not ncpu_data:
# We need at least one CPU to run
return 1
else:
return _number(ncpu_data)
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_nproc,
'Darwin': generic_nproc,
'FreeBSD': generic_nproc,
'OpenBSD': generic_nproc,
'AIX': _aix_nproc,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netstats():
'''
Return the network stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.netstats
'''
def linux_netstats():
'''
linux specific netstats implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
headers = ['']
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
else:
headers = comps
return ret
def freebsd_netstats():
return bsd_netstats()
def bsd_netstats():
'''
bsd specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
if line.startswith('\t\t'):
continue # Skip, too detailed
if not line.startswith('\t'):
key = line.split()[0].replace(':', '')
ret[key] = {}
else:
comps = line.split()
if comps[0].isdigit():
ret[key][' '.join(comps[1:])] = comps[0]
return ret
def sunos_netstats():
'''
sunos specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
line = line.replace('=', ' = ').split()
if len(line) > 6:
line.pop(0)
if '=' in line:
if len(line) >= 3:
if line[2].isdigit() or line[2][0] == '-':
line[2] = _number(line[2])
ret[line[0]] = line[2]
if len(line) >= 6:
if line[5].isdigit() or line[5][0] == '-':
line[5] = _number(line[5])
ret[line[3]] = line[5]
return ret
def aix_netstats():
'''
AIX specific netstats implementation
'''
ret = {}
fields = []
procn = None
proto_name = None
for line in __salt__['cmd.run']('netstat -s').splitlines():
if not line:
continue
if not re.match(r'\s', line) and ':' in line:
comps = line.split(':')
proto_name = comps[0]
ret[proto_name] = []
procn = len(ret[proto_name])
ret[proto_name].append({})
continue
else:
comps = line.split()
comps[0] = comps[0].strip()
if comps[0].isdigit():
ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])
else:
continue
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netstats,
'FreeBSD': bsd_netstats,
'OpenBSD': bsd_netstats,
'SunOS': sunos_netstats,
'AIX': aix_netstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific implementation of netdev
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
if line.find(':') < 0:
continue
comps = line.split()
# Fix lines like eth0:9999..'
comps[0] = line.split(':')[0].strip()
# Support lines both like eth0:999 and eth0: 9999
comps.insert(1, line.split(':')[1].strip().split()[0])
ret[comps[0]] = {'iface': comps[0],
'rx_bytes': _number(comps[2]),
'rx_compressed': _number(comps[8]),
'rx_drop': _number(comps[5]),
'rx_errs': _number(comps[4]),
'rx_fifo': _number(comps[6]),
'rx_frame': _number(comps[7]),
'rx_multicast': _number(comps[9]),
'rx_packets': _number(comps[3]),
'tx_bytes': _number(comps[10]),
'tx_carrier': _number(comps[16]),
'tx_colls': _number(comps[15]),
'tx_compressed': _number(comps[17]),
'tx_drop': _number(comps[13]),
'tx_errs': _number(comps[12]),
'tx_fifo': _number(comps[14]),
'tx_packets': _number(comps[11])}
return ret
def freebsd_netdev():
'''
freebsd specific implementation of netdev
'''
_dict_tree = lambda: collections.defaultdict(_dict_tree)
ret = _dict_tree()
netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()
netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]
header = netstat[0].split()
for line in netstat[1:]:
comps = line.split()
for i in range(4, 13): # The columns we want
ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])
return ret
def sunos_netdev():
'''
sunos specific implementation of netdev
'''
ret = {}
##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:
# fetch device info
netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()
# prepare data
netstat_ipv4[0] = netstat_ipv4[0].split()
netstat_ipv4[1] = netstat_ipv4[1].split()
netstat_ipv6[0] = netstat_ipv6[0].split()
netstat_ipv6[1] = netstat_ipv6[1].split()
# add data
ret[dev] = {}
for i in range(len(netstat_ipv4[0])-1):
if netstat_ipv4[0][i] == 'Name':
continue
if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]
else:
ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])
for i in range(len(netstat_ipv6[0])-1):
if netstat_ipv6[0][i] == 'Name':
continue
if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]
else:
ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])
return ret
def aix_netdev():
'''
AIX specific implementation of netdev
'''
ret = {}
fields = []
procn = None
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():
# fetch device info
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0
#en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0
netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()
# add data
ret[dev] = []
for line in netstat_ipv4:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv4'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv4'][fields[i]] = comps[i]
for line in netstat_ipv6:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv6'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv6'][fields[i]] = comps[i]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netdev,
'FreeBSD': freebsd_netdev,
'SunOS': sunos_netdev,
'AIX': aix_netdev,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def w(): # pylint: disable=C0103
'''
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
'''
def linux_w():
'''
Linux specific implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -fh').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'idle': comps[3],
'jcpu': comps[4],
'login': comps[2],
'pcpu': comps[5],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[6:])}
user_list.append(rec)
return user_list
def bsd_w():
'''
Generic BSD implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -h').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'from': comps[2],
'idle': comps[4],
'login': comps[3],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[5:])}
user_list.append(rec)
return user_list
# dict that returns a function that does the right thing per platform
get_version = {
'Darwin': bsd_w,
'FreeBSD': bsd_w,
'Linux': linux_w,
'OpenBSD': bsd_w,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def all_status():
'''
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
'''
return {'cpuinfo': cpuinfo(),
'cpustats': cpustats(),
'diskstats': diskstats(),
'diskusage': diskusage(),
'loadavg': loadavg(),
'meminfo': meminfo(),
'netdev': netdev(),
'netstats': netstats(),
'uptime': uptime(),
'vmstats': vmstats(),
'w': w()}
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
'''
cmd = __grains__['ps']
output = __salt__['cmd.run_stdout'](cmd, python_shell=True)
pids = ''
for line in output.splitlines():
if 'status.pid' in line:
continue
if re.search(sig, line):
if pids:
pids += '\n'
pids += line.split()[1]
return pids
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
'''
linux specific implementation of version
'''
try:
with salt.utils.files.fopen('/proc/version', 'r') as fp_:
return salt.utils.stringutils.to_unicode(fp_.read()).strip()
except IOError:
return {}
def bsd_version():
'''
bsd specific implementation of version
'''
return __salt__['cmd.run']('sysctl -n kern.version')
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_version,
'FreeBSD': bsd_version,
'OpenBSD': bsd_version,
'AIX': lambda: __salt__['cmd.run']('oslevel -s'),
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def master(master=None, connected=True):
'''
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
master_ips = None
if master:
master_ips = salt.utils.network.host_to_ips(master)
if not master_ips:
return
master_connection_status = False
port = __salt__['config.get']('publish_port', default=4505)
connected_ips = salt.utils.network.remote_port_tcp(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
def proxy_reconnect(proxy_name, opts=None):
'''
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
'''
if not opts:
opts = __opts__
if 'proxy' not in opts:
return False # fail
proxy_keepalive_fn = proxy_name+'.alive'
if proxy_keepalive_fn not in __proxy__:
return False # fail
is_alive = __proxy__[proxy_keepalive_fn](opts)
if not is_alive:
minion_id = opts.get('proxyid', '') or opts.get('id', '')
log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name)
__proxy__[proxy_name+'.shutdown'](opts) # safely close connection
__proxy__[proxy_name+'.init'](opts) # reopen connection
log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name)
return True # success
def time_(format='%A, %d. %B %Y %I:%M%p'):
'''
.. versionadded:: 2016.3.0
Return the current time on the minion,
formatted based on the format parameter.
Default date format: Monday, 27. July 2015 07:55AM
CLI Example:
.. code-block:: bash
salt '*' status.time
salt '*' status.time '%s'
'''
dt = datetime.datetime.today()
return dt.strftime(format)
|
saltstack/salt
|
salt/modules/status.py
|
proxy_reconnect
|
python
|
def proxy_reconnect(proxy_name, opts=None):
'''
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
'''
if not opts:
opts = __opts__
if 'proxy' not in opts:
return False # fail
proxy_keepalive_fn = proxy_name+'.alive'
if proxy_keepalive_fn not in __proxy__:
return False # fail
is_alive = __proxy__[proxy_keepalive_fn](opts)
if not is_alive:
minion_id = opts.get('proxyid', '') or opts.get('id', '')
log.info('%s (%s proxy) is down. Restarting.', minion_id, proxy_name)
__proxy__[proxy_name+'.shutdown'](opts) # safely close connection
__proxy__[proxy_name+'.init'](opts) # reopen connection
log.debug('Restarted %s (%s proxy)!', minion_id, proxy_name)
return True
|
Forces proxy minion reconnection when not alive.
proxy_name
The virtual name of the proxy module.
opts: None
Opts dictionary. Not intended for CLI usage.
CLI Example:
salt '*' status.proxy_reconnect rest_sample
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/status.py#L1686-L1719
| null |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import os
import re
import logging
import fnmatch
import collections
import copy
import time
import logging
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.config
import salt.minion
import salt.utils.event
import salt.utils.files
import salt.utils.network
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.moves import zip
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__file__)
__virtualname__ = 'status'
__opts__ = {}
# Don't shadow built-in's.
__func_alias__ = {
'time_': 'time'
}
log = logging.getLogger(__name__)
def __virtual__():
'''
Not all functions supported by Windows
'''
if salt.utils.platform.is_windows():
return False, 'Windows platform is not supported by this module'
return __virtualname__
def _number(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
if text.isdigit():
return int(text)
try:
return float(text)
except ValueError:
return text
def _get_boot_time_aix():
'''
Return the number of seconds since boot time on AIX
t=$(LC_ALL=POSIX ps -o etime= -p 1)
d=0 h=0
case $t in *-*) d=${t%%-*}; t=${t#*-};; esac
case $t in *:*:*) h=${t%%:*}; t=${t#*:};; esac
s=$((d*86400 + h*3600 + ${t%%:*}*60 + ${t#*:}))
t is 7-20:46:46
'''
boot_secs = 0
res = __salt__['cmd.run_all']('ps -o etime= -p 1')
if res['retcode'] > 0:
raise CommandExecutionError('Unable to find boot_time for pid 1.')
bt_time = res['stdout']
days = bt_time.split('-')
hms = days[1].split(':')
boot_secs = _number(days[0]) * 86400 + _number(hms[0]) * 3600 + _number(hms[1]) * 60 + _number(hms[2])
return boot_secs
def _aix_loadavg():
'''
Return the load average on AIX
'''
# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69
uptime = __salt__['cmd.run']('uptime')
ldavg = uptime.split('load average')
load_avg = ldavg[1].split()
return {'1-min': load_avg[1].strip(','),
'5-min': load_avg[2].strip(','),
'15-min': load_avg[3]}
def _aix_nproc():
'''
Return the maximun number of PROCESSES allowed per user on AIX
'''
nprocs = __salt__['cmd.run']('lsattr -E -l sys0 | grep maxuproc', python_shell=True).split()
return _number(nprocs[1])
def procs():
'''
Return the process data
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.procs
'''
# Get the user, pid and cmd
ret = {}
uind = 0
pind = 0
cind = 0
plines = __salt__['cmd.run'](__grains__['ps'], python_shell=True).splitlines()
guide = plines.pop(0).split()
if 'USER' in guide:
uind = guide.index('USER')
elif 'UID' in guide:
uind = guide.index('UID')
if 'PID' in guide:
pind = guide.index('PID')
if 'COMMAND' in guide:
cind = guide.index('COMMAND')
elif 'CMD' in guide:
cind = guide.index('CMD')
for line in plines:
if not line:
continue
comps = line.split()
ret[comps[pind]] = {'user': comps[uind],
'cmd': ' '.join(comps[cind:])}
return ret
def custom():
'''
Return a custom composite of status data and info for this minion,
based on the minion config file. An example config like might be::
status.cpustats.custom: [ 'cpu', 'ctxt', 'btime', 'processes' ]
Where status refers to status.py, cpustats is the function
where we get our data, and custom is this function It is followed
by a list of keys that we want returned.
This function is meant to replace all_status(), which returns
anything and everything, which we probably don't want.
By default, nothing is returned. Warning: Depending on what you
include, there can be a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.custom
'''
ret = {}
conf = __salt__['config.dot_vals']('status')
for key, val in six.iteritems(conf):
func = '{0}()'.format(key.split('.')[1])
vals = eval(func) # pylint: disable=W0123
for item in val:
ret[item] = vals[item]
return ret
def uptime():
'''
Return the uptime for this system.
.. versionchanged:: 2015.8.9
The uptime function was changed to return a dictionary of easy-to-read
key/value pairs containing uptime information, instead of the output
from a ``cmd.run`` call.
.. versionchanged:: 2016.11.0
Support for OpenBSD, FreeBSD, NetBSD, MacOS, and Solaris
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.uptime
'''
curr_seconds = time.time()
# Get uptime in seconds
if salt.utils.platform.is_linux():
ut_path = "/proc/uptime"
if not os.path.exists(ut_path):
raise CommandExecutionError("File {ut_path} was not found.".format(ut_path=ut_path))
with salt.utils.files.fopen(ut_path) as rfh:
seconds = int(float(rfh.read().split()[0]))
elif salt.utils.platform.is_sunos():
# note: some flavors/versions report the host uptime inside a zone
# https://support.oracle.com/epmos/faces/BugDisplay?id=15611584
res = __salt__['cmd.run_all']('kstat -p unix:0:system_misc:boot_time')
if res['retcode'] > 0:
raise CommandExecutionError('The boot_time kstat was not found.')
seconds = int(curr_seconds - int(res['stdout'].split()[-1]))
elif salt.utils.platform.is_openbsd() or salt.utils.platform.is_netbsd():
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
seconds = int(curr_seconds - int(bt_data))
elif salt.utils.platform.is_freebsd() or salt.utils.platform.is_darwin():
# format: { sec = 1477761334, usec = 664698 } Sat Oct 29 17:15:34 2016
bt_data = __salt__['sysctl.get']('kern.boottime')
if not bt_data:
raise CommandExecutionError('Cannot find kern.boottime system parameter')
data = bt_data.split("{")[-1].split("}")[0].strip().replace(' ', '')
uptime = dict([(k, int(v,)) for k, v in [p.strip().split('=') for p in data.split(',')]])
seconds = int(curr_seconds - uptime['sec'])
elif salt.utils.platform.is_aix():
seconds = _get_boot_time_aix()
else:
return __salt__['cmd.run']('uptime')
# Setup datetime and timedelta objects
boot_time = datetime.datetime.utcfromtimestamp(curr_seconds - seconds)
curr_time = datetime.datetime.utcfromtimestamp(curr_seconds)
up_time = curr_time - boot_time
# Construct return information
ut_ret = {
'seconds': seconds,
'since_iso': boot_time.isoformat(),
'since_t': int(curr_seconds - seconds),
'days': up_time.days,
'time': '{0}:{1}'.format(up_time.seconds // 3600, up_time.seconds % 3600 // 60),
}
if salt.utils.path.which('who'):
who_cmd = 'who' if salt.utils.platform.is_openbsd() else 'who -s' # OpenBSD does not support -s
ut_ret['users'] = len(__salt__['cmd.run'](who_cmd).split(os.linesep))
return ut_ret
def loadavg():
'''
Return the load averages for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.loadavg
:raises CommandExecutionError: If the system cannot report loadaverages to Python
'''
if __grains__['kernel'] == 'AIX':
return _aix_loadavg()
try:
load_avg = os.getloadavg()
except AttributeError:
# Some UNIX-based operating systems do not have os.getloadavg()
raise salt.exceptions.CommandExecutionError('status.loadavag is not available on your platform')
return {'1-min': load_avg[0],
'5-min': load_avg[1],
'15-min': load_avg[2]}
def cpustats():
'''
Return the CPU stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpustats
'''
def linux_cpustats():
'''
linux specific implementation of cpustats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/stat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == 'cpu':
ret[comps[0]] = {'idle': _number(comps[4]),
'iowait': _number(comps[5]),
'irq': _number(comps[6]),
'nice': _number(comps[2]),
'softirq': _number(comps[7]),
'steal': _number(comps[8]),
'system': _number(comps[3]),
'user': _number(comps[1])}
elif comps[0] == 'intr':
ret[comps[0]] = {'total': _number(comps[1]),
'irqs': [_number(x) for x in comps[2:]]}
elif comps[0] == 'softirq':
ret[comps[0]] = {'total': _number(comps[1]),
'softirqs': [_number(x) for x in comps[2:]]}
else:
ret[comps[0]] = _number(comps[1])
return ret
def freebsd_cpustats():
'''
freebsd specific implementation of cpustats
'''
vmstat = __salt__['cmd.run']('vmstat -P').splitlines()
vm0 = vmstat[0].split()
cpu0loc = vm0.index('cpu0')
vm1 = vmstat[1].split()
usloc = vm1.index('us')
vm2 = vmstat[2].split()
cpuctr = 0
ret = {}
for cpu in vm0[cpu0loc:]:
ret[cpu] = {'us': _number(vm2[usloc + 3 * cpuctr]),
'sy': _number(vm2[usloc + 1 + 3 * cpuctr]),
'id': _number(vm2[usloc + 2 + 3 * cpuctr]), }
cpuctr += 1
return ret
def sunos_cpustats():
'''
sunos specific implementation of cpustats
'''
mpstat = __salt__['cmd.run']('mpstat 1 2').splitlines()
fields = mpstat[0].split()
ret = {}
for cpu in mpstat:
if cpu.startswith('CPU'):
continue
cpu = cpu.split()
ret[_number(cpu[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpu[0])][fields[i]] = _number(cpu[i])
return ret
def aix_cpustats():
'''
AIX specific implementation of cpustats
'''
ret = {}
ret['mpstat'] = []
procn = None
fields = []
for line in __salt__['cmd.run']('mpstat -a').splitlines():
if not line:
continue
procn = len(ret['mpstat'])
if line.startswith('System'):
comps = line.split(':')
ret['mpstat'].append({})
ret['mpstat'][procn]['system'] = {}
cpu_comps = comps[1].split()
for i in range(0, len(cpu_comps)):
cpu_vals = cpu_comps[i].split('=')
ret['mpstat'][procn]['system'][cpu_vals[0]] = cpu_vals[1]
if line.startswith('cpu'):
fields = line.split()
continue
if fields:
cpustat = line.split()
ret[_number(cpustat[0])] = {}
for i in range(1, len(fields)-1):
ret[_number(cpustat[0])][fields[i]] = _number(cpustat[i])
return ret
def openbsd_cpustats():
'''
openbsd specific implementation of cpustats
'''
systat = __salt__['cmd.run']('systat -s 2 -B cpu').splitlines()
fields = systat[3].split()
ret = {}
for cpu in systat[4:]:
cpu_line = cpu.split()
cpu_idx = cpu_line[0]
ret[cpu_idx] = {}
for idx, field in enumerate(fields[1:]):
ret[cpu_idx][field] = cpu_line[idx+1]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_cpustats,
'FreeBSD': freebsd_cpustats,
'OpenBSD': openbsd_cpustats,
'SunOS': sunos_cpustats,
'AIX': aix_cpustats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def meminfo():
'''
Return the memory info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.meminfo
'''
def linux_meminfo():
'''
linux specific implementation of meminfo
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
comps[0] = comps[0].replace(':', '')
ret[comps[0]] = {
'value': comps[1],
}
if len(comps) > 2:
ret[comps[0]]['unit'] = comps[2]
return ret
def freebsd_meminfo():
'''
freebsd specific implementation of meminfo
'''
sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
sysctlvm = [x.split(':') for x in sysctlvm]
sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
sysctlvm = [x for x in sysctlvm if x[1]] # If x[1] not empty
ret = {}
for line in sysctlvm:
ret[line[0]] = line[1]
# Special handling for vm.total as it's especially important
sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
sysctlvmtot = [x for x in sysctlvmtot if x]
ret['vm.vmtotal'] = sysctlvmtot
return ret
def aix_meminfo():
'''
AIX specific implementation of meminfo
'''
ret = {}
ret['svmon'] = []
ret['vmstat'] = []
procn = None
fields = []
pagesize_flag = False
for line in __salt__['cmd.run']('svmon -G').splitlines():
# Note: svmon is per-system
# size inuse free pin virtual mmode
#memory 1048576 1039740 8836 285078 474993 Ded
#pg space 917504 2574
#
# work pers clnt other
#pin 248379 0 2107 34592
#in use 474993 0 564747
#
#PageSize PoolSize inuse pgsp pin virtual
#s 4 KB - 666956 2574 60726 102209
#m 64 KB - 23299 0 14022 23299
if not line:
continue
if re.match(r'\s', line):
# assume fields line
fields = line.split()
continue
if line.startswith('memory') or line.startswith('pin'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i + 1:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
continue
if line.startswith('pg space') or line.startswith('in use'):
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
pg_space = '{0} {1}'.format(comps[0], comps[1])
ret['svmon'][procn][pg_space] = {}
for i in range(0, len(fields)):
if len(comps) > i + 2:
ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
continue
if line.startswith('PageSize'):
fields = line.split()
pagesize_flag = False
continue
if pagesize_flag:
procn = len(ret['svmon'])
ret['svmon'].append({})
comps = line.split()
ret['svmon'][procn][comps[0]] = {}
for i in range(0, len(fields)):
if len(comps) > i:
ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
continue
for line in __salt__['cmd.run']('vmstat -v').splitlines():
# Note: vmstat is per-system
if not line:
continue
procn = len(ret['vmstat'])
ret['vmstat'].append({})
comps = line.lstrip().split(' ', 1)
ret['vmstat'][procn][comps[1]] = comps[0]
return ret
def openbsd_meminfo():
'''
openbsd specific implementation of meminfo
'''
vmstat = __salt__['cmd.run']('vmstat').splitlines()
# We're only interested in memory and page values which are printed
# as subsequent fields.
fields = ['active virtual pages', 'free list size', 'page faults',
'pages reclaimed', 'pages paged in', 'pages paged out',
'pages freed', 'pages scanned']
data = vmstat[2].split()[2:10]
ret = dict(zip(fields, data))
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_meminfo,
'FreeBSD': freebsd_meminfo,
'OpenBSD': openbsd_meminfo,
'AIX': aix_meminfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def cpuinfo():
'''
.. versionchanged:: 2016.3.2
Return the CPU info for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for NetBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.cpuinfo
'''
def linux_cpuinfo():
'''
linux specific cpuinfo implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
if comps[0] == 'flags':
ret[comps[0]] = comps[1].split()
else:
ret[comps[0]] = comps[1].strip()
return ret
def bsd_cpuinfo():
'''
bsd specific cpuinfo implementation
'''
bsd_cmd = 'sysctl hw.model hw.ncpu'
ret = {}
if __grains__['kernel'].lower() in ['netbsd', 'openbsd']:
sep = '='
else:
sep = ':'
for line in __salt__['cmd.run'](bsd_cmd).splitlines():
if not line:
continue
comps = line.split(sep)
comps[0] = comps[0].strip()
ret[comps[0]] = comps[1].strip()
return ret
def sunos_cpuinfo():
'''
sunos specific cpuinfo implementation
'''
ret = {}
ret['isainfo'] = {}
for line in __salt__['cmd.run']('isainfo -x').splitlines():
# Note: isainfo is per-system and not per-cpu
# Output Example:
#amd64: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp cx16 sse3 sse2 sse fxsr mmx cmov amd_sysc cx8 tsc fpu
#i386: rdrand f16c vmx avx xsave pclmulqdq aes sse4.2 sse4.1 ssse3 popcnt tscp ahf cx16 sse3 sse2 sse fxsr mmx cmov sep cx8 tsc fpu
if not line:
continue
comps = line.split(':')
comps[0] = comps[0].strip()
ret['isainfo'][comps[0]] = sorted(comps[1].strip().split())
ret['psrinfo'] = []
procn = None
for line in __salt__['cmd.run']('psrinfo -v -p').splitlines():
# Output Example:
#The physical processor has 6 cores and 12 virtual processors (0-5 12-17)
# The core has 2 virtual processors (0 12)
# The core has 2 virtual processors (1 13)
# The core has 2 virtual processors (2 14)
# The core has 2 virtual processors (3 15)
# The core has 2 virtual processors (4 16)
# The core has 2 virtual processors (5 17)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#The physical processor has 6 cores and 12 virtual processors (6-11 18-23)
# The core has 2 virtual processors (6 18)
# The core has 2 virtual processors (7 19)
# The core has 2 virtual processors (8 20)
# The core has 2 virtual processors (9 21)
# The core has 2 virtual processors (10 22)
# The core has 2 virtual processors (11 23)
# x86 (GenuineIntel 306E4 family 6 model 62 step 4 clock 2100 MHz)
# Intel(r) Xeon(r) CPU E5-2620 v2 @ 2.10GHz
#
# Output Example 2:
#The physical processor has 4 virtual processors (0-3)
# x86 (GenuineIntel 406D8 family 6 model 77 step 8 clock 2400 MHz)
# Intel(r) Atom(tm) CPU C2558 @ 2.40GHz
if not line:
continue
if line.startswith('The physical processor'):
procn = len(ret['psrinfo'])
line = line.split()
ret['psrinfo'].append({})
if 'cores' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['cores'] = _number(line[4])
ret['psrinfo'][procn]['topology']['threads'] = _number(line[7])
elif 'virtual' in line:
ret['psrinfo'][procn]['topology'] = {}
ret['psrinfo'][procn]['topology']['threads'] = _number(line[4])
elif line.startswith(' ' * 6): # 3x2 space indent
ret['psrinfo'][procn]['name'] = line.strip()
elif line.startswith(' ' * 4): # 2x2 space indent
line = line.strip().split()
ret['psrinfo'][procn]['vendor'] = line[1][1:]
ret['psrinfo'][procn]['family'] = _number(line[4])
ret['psrinfo'][procn]['model'] = _number(line[6])
ret['psrinfo'][procn]['step'] = _number(line[8])
ret['psrinfo'][procn]['clock'] = "{0} {1}".format(line[10], line[11][:-1])
return ret
def aix_cpuinfo():
'''
AIX specific cpuinfo implementation
'''
ret = {}
ret['prtconf'] = []
ret['lparstat'] = []
procn = None
for line in __salt__['cmd.run']('prtconf | grep -i "Processor"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#prtconf | grep -i "Processor"
#Processor Type: PowerPC_POWER7
#Processor Implementation Mode: POWER 7
#Processor Version: PV_7_Compat
#Number Of Processors: 2
#Processor Clock Speed: 3000 MHz
# Model Implementation: Multiple Processor, PCI bus
# + proc0 Processor
# + proc4 Processor
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('Processor') or line.startswith('Number'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('prtconf | grep "CPU"', python_shell=True).splitlines():
# Note: prtconf is per-system and not per-cpu
# Output Example:
#CPU Type: 64-bit
if not line:
continue
procn = len(ret['prtconf'])
if line.startswith('CPU'):
ret['prtconf'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['prtconf'][procn][comps[0]] = comps[1]
else:
continue
for line in __salt__['cmd.run']('lparstat -i | grep CPU', python_shell=True).splitlines():
# Note: lparstat is per-system and not per-cpu
# Output Example:
#Online Virtual CPUs : 2
#Maximum Virtual CPUs : 2
#Minimum Virtual CPUs : 1
#Maximum Physical CPUs in system : 32
#Active Physical CPUs in system : 32
#Active CPUs in Pool : 32
#Shared Physical CPUs in system : 32
#Physical CPU Percentage : 25.00%
#Desired Virtual CPUs : 2
if not line:
continue
procn = len(ret['lparstat'])
ret['lparstat'].append({})
comps = line.split(':')
comps[0] = comps[0].rstrip()
ret['lparstat'][procn][comps[0]] = comps[1]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_cpuinfo,
'FreeBSD': bsd_cpuinfo,
'NetBSD': bsd_cpuinfo,
'OpenBSD': bsd_cpuinfo,
'SunOS': sunos_cpuinfo,
'AIX': aix_cpuinfo,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific implementation of diskstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/diskstats', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[2]] = {
'major': _number(comps[0]),
'minor': _number(comps[1]),
'device': _number(comps[2]),
'reads_issued': _number(comps[3]),
'reads_merged': _number(comps[4]),
'sectors_read': _number(comps[5]),
'ms_spent_reading': _number(comps[6]),
'writes_completed': _number(comps[7]),
'writes_merged': _number(comps[8]),
'sectors_written': _number(comps[9]),
'ms_spent_writing': _number(comps[10]),
'io_in_progress': _number(comps[11]),
'ms_spent_in_io': _number(comps[12]),
'weighted_ms_spent_in_io': _number(comps[13])
}
return ret
def generic_diskstats():
'''
generic implementation of diskstats
note: freebsd and sunos
'''
ret = {}
iostat = __salt__['cmd.run']('iostat -xzd').splitlines()
header = iostat[1]
for line in iostat[2:]:
comps = line.split()
ret[comps[0]] = {}
for metric, value in zip(header.split()[1:], comps[1:]):
ret[comps[0]][metric] = _number(value)
return ret
def aix_diskstats():
'''
AIX specific implementation of diskstats
'''
ret = {}
procn = None
fields = []
disk_name = ''
disk_mode = ''
for line in __salt__['cmd.run']('iostat -dDV').splitlines():
# Note: iostat -dDV is per-system
#
#System configuration: lcpu=8 drives=1 paths=2 vdisks=2
#
#hdisk0 xfer: %tm_act bps tps bread bwrtn
# 0.0 0.8 0.0 0.0 0.8
# read: rps avgserv minserv maxserv timeouts fails
# 0.0 2.5 0.3 12.4 0 0
# write: wps avgserv minserv maxserv timeouts fails
# 0.0 0.3 0.2 0.7 0 0
# queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull
# 0.3 0.0 5.3 0.0 0.0 0.0
#--------------------------------------------------------------------------------
if not line or line.startswith('System') or line.startswith('-----------'):
continue
if not re.match(r'\s', line):
#have new disk
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()
ret[disk_name] = []
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
continue
if ':' in line:
comps = line.split(':')
fields = comps[1].split()
disk_mode = comps[0].lstrip()
procn = len(ret[disk_name])
ret[disk_name].append({})
ret[disk_name][procn][disk_mode] = {}
else:
comps = line.split()
for i in range(0, len(fields)):
if len(comps) > i:
ret[disk_name][procn][disk_mode][fields[i]] = comps[i]
return ret
# dict that return a function that does the right thing per platform
get_version = {
'Linux': linux_diskstats,
'FreeBSD': generic_diskstats,
'SunOS': generic_diskstats,
'AIX': aix_diskstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def diskusage(*args):
'''
Return the disk usage for this minion
Usage::
salt '*' status.diskusage [paths and/or filesystem types]
CLI Example:
.. code-block:: bash
salt '*' status.diskusage # usage for all filesystems
salt '*' status.diskusage / /tmp # usage for / and /tmp
salt '*' status.diskusage ext? # usage for ext[234] filesystems
salt '*' status.diskusage / ext? # usage for / and all ext filesystems
'''
selected = set()
fstypes = set()
if not args:
# select all filesystems
fstypes.add('*')
else:
for arg in args:
if arg.startswith('/'):
# select path
selected.add(arg)
else:
# select fstype
fstypes.add(arg)
if fstypes:
# determine which mount points host the specified fstypes
regex = re.compile(
'|'.join(
fnmatch.translate(fstype).format('(%s)') for fstype in fstypes
)
)
# ifile source of data varies with OS, otherwise all the same
if __grains__['kernel'] == 'Linux':
try:
with salt.utils.files.fopen('/proc/mounts', 'r') as fp_:
ifile = salt.utils.stringutils.to_unicode(fp_.read()).splitlines()
except OSError:
return {}
elif __grains__['kernel'] in ('FreeBSD', 'SunOS'):
ifile = __salt__['cmd.run']('mount -p').splitlines()
else:
raise CommandExecutionError('status.diskusage not yet supported on this platform')
for line in ifile:
comps = line.split()
if __grains__['kernel'] == 'SunOS':
if len(comps) >= 4:
mntpt = comps[2]
fstype = comps[3]
if regex.match(fstype):
selected.add(mntpt)
else:
if len(comps) >= 3:
mntpt = comps[1]
fstype = comps[2]
if regex.match(fstype):
selected.add(mntpt)
# query the filesystems disk usage
ret = {}
for path in selected:
fsstats = os.statvfs(path)
blksz = fsstats.f_bsize
available = fsstats.f_bavail * blksz
total = fsstats.f_blocks * blksz
ret[path] = {"available": available, "total": total}
return ret
def vmstats():
'''
.. versionchanged:: 2016.3.2
Return the virtual memory stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.vmstats
'''
def linux_vmstats():
'''
linux specific implementation of vmstats
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/vmstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
comps = line.split()
ret[comps[0]] = _number(comps[1])
return ret
def generic_vmstats():
'''
generic implementation of vmstats
note: works on FreeBSD, SunOS and OpenBSD (possibly others)
'''
ret = {}
for line in __salt__['cmd.run']('vmstat -s').splitlines():
comps = line.split()
if comps[0].isdigit():
ret[' '.join(comps[1:])] = _number(comps[0].strip())
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_vmstats,
'FreeBSD': generic_vmstats,
'OpenBSD': generic_vmstats,
'SunOS': generic_vmstats,
'AIX': generic_vmstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def nproc():
'''
Return the number of processing units available on this system
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for Darwin, FreeBSD and OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.nproc
'''
def linux_nproc():
'''
linux specific implementation of nproc
'''
try:
return _number(__salt__['cmd.run']('nproc').strip())
except ValueError:
return 0
def generic_nproc():
'''
generic implementation of nproc
'''
ncpu_data = __salt__['sysctl.get']('hw.ncpu')
if not ncpu_data:
# We need at least one CPU to run
return 1
else:
return _number(ncpu_data)
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_nproc,
'Darwin': generic_nproc,
'FreeBSD': generic_nproc,
'OpenBSD': generic_nproc,
'AIX': _aix_nproc,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netstats():
'''
Return the network stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.netstats
'''
def linux_netstats():
'''
linux specific netstats implementation
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/netstat', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
headers = ['']
for line in stats.splitlines():
if not line:
continue
comps = line.split()
if comps[0] == headers[0]:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = _number(comps[field])
rowname = headers[0].replace(':', '')
ret[rowname] = row
else:
headers = comps
return ret
def freebsd_netstats():
return bsd_netstats()
def bsd_netstats():
'''
bsd specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
if line.startswith('\t\t'):
continue # Skip, too detailed
if not line.startswith('\t'):
key = line.split()[0].replace(':', '')
ret[key] = {}
else:
comps = line.split()
if comps[0].isdigit():
ret[key][' '.join(comps[1:])] = comps[0]
return ret
def sunos_netstats():
'''
sunos specific netstats implementation
'''
ret = {}
for line in __salt__['cmd.run']('netstat -s').splitlines():
line = line.replace('=', ' = ').split()
if len(line) > 6:
line.pop(0)
if '=' in line:
if len(line) >= 3:
if line[2].isdigit() or line[2][0] == '-':
line[2] = _number(line[2])
ret[line[0]] = line[2]
if len(line) >= 6:
if line[5].isdigit() or line[5][0] == '-':
line[5] = _number(line[5])
ret[line[3]] = line[5]
return ret
def aix_netstats():
'''
AIX specific netstats implementation
'''
ret = {}
fields = []
procn = None
proto_name = None
for line in __salt__['cmd.run']('netstat -s').splitlines():
if not line:
continue
if not re.match(r'\s', line) and ':' in line:
comps = line.split(':')
proto_name = comps[0]
ret[proto_name] = []
procn = len(ret[proto_name])
ret[proto_name].append({})
continue
else:
comps = line.split()
comps[0] = comps[0].strip()
if comps[0].isdigit():
ret[proto_name][procn][' '.join(comps[1:])] = _number(comps[0])
else:
continue
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netstats,
'FreeBSD': bsd_netstats,
'OpenBSD': bsd_netstats,
'SunOS': sunos_netstats,
'AIX': aix_netstats,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def netdev():
'''
.. versionchanged:: 2016.3.2
Return the network device stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.netdev
'''
def linux_netdev():
'''
linux specific implementation of netdev
'''
ret = {}
try:
with salt.utils.files.fopen('/proc/net/dev', 'r') as fp_:
stats = salt.utils.stringutils.to_unicode(fp_.read())
except IOError:
pass
else:
for line in stats.splitlines():
if not line:
continue
if line.find(':') < 0:
continue
comps = line.split()
# Fix lines like eth0:9999..'
comps[0] = line.split(':')[0].strip()
# Support lines both like eth0:999 and eth0: 9999
comps.insert(1, line.split(':')[1].strip().split()[0])
ret[comps[0]] = {'iface': comps[0],
'rx_bytes': _number(comps[2]),
'rx_compressed': _number(comps[8]),
'rx_drop': _number(comps[5]),
'rx_errs': _number(comps[4]),
'rx_fifo': _number(comps[6]),
'rx_frame': _number(comps[7]),
'rx_multicast': _number(comps[9]),
'rx_packets': _number(comps[3]),
'tx_bytes': _number(comps[10]),
'tx_carrier': _number(comps[16]),
'tx_colls': _number(comps[15]),
'tx_compressed': _number(comps[17]),
'tx_drop': _number(comps[13]),
'tx_errs': _number(comps[12]),
'tx_fifo': _number(comps[14]),
'tx_packets': _number(comps[11])}
return ret
def freebsd_netdev():
'''
freebsd specific implementation of netdev
'''
_dict_tree = lambda: collections.defaultdict(_dict_tree)
ret = _dict_tree()
netstat = __salt__['cmd.run']('netstat -i -n -4 -b -d').splitlines()
netstat += __salt__['cmd.run']('netstat -i -n -6 -b -d').splitlines()[1:]
header = netstat[0].split()
for line in netstat[1:]:
comps = line.split()
for i in range(4, 13): # The columns we want
ret[comps[0]][comps[2]][comps[3]][header[i]] = _number(comps[i])
return ret
def sunos_netdev():
'''
sunos specific implementation of netdev
'''
ret = {}
##NOTE: we cannot use hwaddr_interfaces here, so we grab both ip4 and ip6
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces']:
# fetch device info
netstat_ipv4 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -I {dev} -n -f inet6'.format(dev=dev)).splitlines()
# prepare data
netstat_ipv4[0] = netstat_ipv4[0].split()
netstat_ipv4[1] = netstat_ipv4[1].split()
netstat_ipv6[0] = netstat_ipv6[0].split()
netstat_ipv6[1] = netstat_ipv6[1].split()
# add data
ret[dev] = {}
for i in range(len(netstat_ipv4[0])-1):
if netstat_ipv4[0][i] == 'Name':
continue
if netstat_ipv4[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv4 {field}'.format(field=netstat_ipv4[0][i])] = netstat_ipv4[1][i]
else:
ret[dev][netstat_ipv4[0][i]] = _number(netstat_ipv4[1][i])
for i in range(len(netstat_ipv6[0])-1):
if netstat_ipv6[0][i] == 'Name':
continue
if netstat_ipv6[0][i] in ['Address', 'Net/Dest']:
ret[dev]['IPv6 {field}'.format(field=netstat_ipv6[0][i])] = netstat_ipv6[1][i]
else:
ret[dev][netstat_ipv6[0][i]] = _number(netstat_ipv6[1][i])
return ret
def aix_netdev():
'''
AIX specific implementation of netdev
'''
ret = {}
fields = []
procn = None
for dev in __grains__['ip4_interfaces'].keys() + __grains__['ip6_interfaces'].keys():
# fetch device info
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029668 0 446490 0 0
#en0 1500 172.29.128 172.29.149.95 10029668 0 446490 0 0
#root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -i -n -I en0 -f inet6
#Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
#en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0
netstat_ipv4 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet'.format(dev=dev)).splitlines()
netstat_ipv6 = __salt__['cmd.run']('netstat -i -n -I {dev} -f inet6'.format(dev=dev)).splitlines()
# add data
ret[dev] = []
for line in netstat_ipv4:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv4'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv4'][fields[i]] = comps[i]
for line in netstat_ipv6:
if line.startswith('Name'):
fields = line.split()
continue
comps = line.split()
if len(comps) < 3:
raise CommandExecutionError('Insufficent data returned by command to process \'{0}\''.format(line))
if comps[2].startswith('link'):
continue
procn = len(ret[dev])
ret[dev].append({})
ret[dev][procn]['ipv6'] = {}
for i in range(1, len(fields)):
if len(comps) > i:
ret[dev][procn]['ipv6'][fields[i]] = comps[i]
return ret
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_netdev,
'FreeBSD': freebsd_netdev,
'SunOS': sunos_netdev,
'AIX': aix_netdev,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def w(): # pylint: disable=C0103
'''
Return a list of logged in users for this minion, using the w command
CLI Example:
.. code-block:: bash
salt '*' status.w
'''
def linux_w():
'''
Linux specific implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -fh').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'idle': comps[3],
'jcpu': comps[4],
'login': comps[2],
'pcpu': comps[5],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[6:])}
user_list.append(rec)
return user_list
def bsd_w():
'''
Generic BSD implementation for w
'''
user_list = []
users = __salt__['cmd.run']('w -h').splitlines()
for row in users:
if not row:
continue
comps = row.split()
rec = {'from': comps[2],
'idle': comps[4],
'login': comps[3],
'tty': comps[1],
'user': comps[0],
'what': ' '.join(comps[5:])}
user_list.append(rec)
return user_list
# dict that returns a function that does the right thing per platform
get_version = {
'Darwin': bsd_w,
'FreeBSD': bsd_w,
'Linux': linux_w,
'OpenBSD': bsd_w,
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def all_status():
'''
Return a composite of all status data and info for this minion.
Warning: There is a LOT here!
CLI Example:
.. code-block:: bash
salt '*' status.all_status
'''
return {'cpuinfo': cpuinfo(),
'cpustats': cpustats(),
'diskstats': diskstats(),
'diskusage': diskusage(),
'loadavg': loadavg(),
'meminfo': meminfo(),
'netdev': netdev(),
'netstats': netstats(),
'uptime': uptime(),
'vmstats': vmstats(),
'w': w()}
def pid(sig):
'''
Return the PID or an empty string if the process is running or not.
Pass a signature to use to find the process via ps. Note you can pass
a Python-compatible regular expression to return all pids of
processes matching the regexp.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.pid <sig>
'''
cmd = __grains__['ps']
output = __salt__['cmd.run_stdout'](cmd, python_shell=True)
pids = ''
for line in output.splitlines():
if 'status.pid' in line:
continue
if re.search(sig, line):
if pids:
pids += '\n'
pids += line.split()[1]
return pids
def version():
'''
Return the system version for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
.. versionchanged:: 2018.3.0
Added support for OpenBSD
CLI Example:
.. code-block:: bash
salt '*' status.version
'''
def linux_version():
'''
linux specific implementation of version
'''
try:
with salt.utils.files.fopen('/proc/version', 'r') as fp_:
return salt.utils.stringutils.to_unicode(fp_.read()).strip()
except IOError:
return {}
def bsd_version():
'''
bsd specific implementation of version
'''
return __salt__['cmd.run']('sysctl -n kern.version')
# dict that returns a function that does the right thing per platform
get_version = {
'Linux': linux_version,
'FreeBSD': bsd_version,
'OpenBSD': bsd_version,
'AIX': lambda: __salt__['cmd.run']('oslevel -s'),
}
errmsg = 'This method is unsupported on the current operating system!'
return get_version.get(__grains__['kernel'], lambda: errmsg)()
def master(master=None, connected=True):
'''
.. versionadded:: 2014.7.0
Return the connection status with master. Fire an event if the
connection to master is not as expected. This function is meant to be
run via a scheduled job from the minion. If master_ip is an FQDN/Hostname,
it must be resolvable to a valid IPv4 address.
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
master_ips = None
if master:
master_ips = salt.utils.network.host_to_ips(master)
if not master_ips:
return
master_connection_status = False
port = __salt__['config.get']('publish_port', default=4505)
connected_ips = salt.utils.network.remote_port_tcp(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
def ping_master(master):
'''
.. versionadded:: 2016.3.0
Sends ping request to the given master. Fires '__master_failback' event on success.
Returns bool result.
CLI Example:
.. code-block:: bash
salt '*' status.ping_master localhost
'''
if master is None or master == '':
return False
opts = copy.deepcopy(__opts__)
opts['master'] = master
if 'master_ip' in opts: # avoid 'master ip changed' warning
del opts['master_ip']
opts.update(salt.minion.prep_ip_port(opts))
try:
opts.update(salt.minion.resolve_dns(opts, fallback=False))
except Exception:
return False
timeout = opts.get('auth_timeout', 60)
load = {'cmd': 'ping'}
result = False
channel = salt.transport.client.ReqChannel.factory(opts, crypt='clear')
try:
payload = channel.send(load, tries=0, timeout=timeout)
result = True
except Exception as e:
pass
if result:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
event.fire_event({'master': master}, salt.minion.master_event(type='failback'))
return result
# success
def time_(format='%A, %d. %B %Y %I:%M%p'):
'''
.. versionadded:: 2016.3.0
Return the current time on the minion,
formatted based on the format parameter.
Default date format: Monday, 27. July 2015 07:55AM
CLI Example:
.. code-block:: bash
salt '*' status.time
salt '*' status.time '%s'
'''
dt = datetime.datetime.today()
return dt.strftime(format)
|
saltstack/salt
|
salt/states/x509.py
|
_revoked_to_list
|
python
|
def _revoked_to_list(revs):
'''
Turn the mess of OrderedDicts and Lists into a list of dicts for
use in the CRL module.
'''
list_ = []
for rev in revs:
for rev_name, props in six.iteritems(
rev): # pylint: disable=unused-variable
dict_ = {}
for prop in props:
for propname, val in six.iteritems(prop):
if isinstance(val, datetime.datetime):
val = val.strftime('%Y-%m-%d %H:%M:%S')
dict_[propname] = val
list_.append(dict_)
return list_
|
Turn the mess of OrderedDicts and Lists into a list of dicts for
use in the CRL module.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/x509.py#L187-L205
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 Certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
This module can enable managing a complete PKI infrastructure including creating private keys, CA's,
certificates and CRLs. It includes the ability to generate a private key on a server, and have the
corresponding public key sent to a remote CA to create a CA signed certificate. This can be done in
a secure manner, where private keys are always generated locally and never moved across the network.
Here is a simple example scenario. In this example ``ca`` is the ca server,
and ``www`` is a web server that needs a certificate signed by ``ca``.
For remote signing, peers must be permitted to remotely call the
:mod:`sign_remote_certificate <salt.modules.x509.sign_remote_certificate>` function.
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
/srv/salt/top.sls
.. code-block:: yaml
base:
'*':
- cert
'ca':
- ca
'www':
- www
This state creates the CA key, certificate and signing policy. It also publishes the certificate to
the mine where it can be easily retrieved by other minions.
/srv/salt/ca.sls
.. code-block:: yaml
salt-minion:
service.running:
- enable: True
- listen:
- file: /etc/salt/minion.d/signing_policies.conf
/etc/salt/minion.d/signing_policies.conf:
file.managed:
- source: salt://signing_policies.conf
/etc/pki:
file.directory
/etc/pki/issued_certs:
file.directory
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
- managed_private_key:
name: /etc/pki/ca.key
bits: 4096
backup: True
- require:
- file: /etc/pki
mine.send:
module.run:
- func: x509.get_pem_entries
- kwargs:
glob_path: /etc/pki/ca.crt
- onchanges:
- x509: /etc/pki/ca.crt
The signing policy defines properties that override any property requested or included in a CRL. It also
can define a restricted list of minons which are allowed to remotely invoke this signing policy.
/srv/salt/signing_policies.conf
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical keyEncipherment"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
This state will instruct all minions to trust certificates signed by our new CA.
Using jinja to strip newlines from the text avoids dealing with newlines in the rendered yaml,
and the :mod:`sign_remote_certificate <salt.states.x509.sign_remote_certificate>` state will
handle properly formatting the text before writing the output.
/srv/salt/cert.sls
.. code-block:: jinja
/usr/local/share/ca-certificates:
file.directory
/usr/local/share/ca-certificates/intca.crt:
x509.pem_managed:
- text: {{ salt['mine.get']('ca', 'x509.get_pem_entries')['ca']['/etc/pki/ca.crt']|replace('\\n', '') }}
This state creates a private key then requests a certificate signed by ca according to the www policy.
/srv/salt/www.sls
.. code-block:: yaml
/etc/pki/www.crt:
x509.certificate_managed:
- ca_server: ca
- signing_policy: www
- public_key: /etc/pki/www.key
- CN: www.example.com
- days_remaining: 30
- backup: True
- managed_private_key:
name: /etc/pki/www.key
bits: 4096
backup: True
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import datetime
import os
import re
import copy
# Import Salt Libs
import salt.exceptions
import salt.utils.stringutils
# Import 3rd-party libs
from salt.ext import six
try:
from M2Crypto.RSA import RSAError
except ImportError:
RSAError = Exception('RSA Error')
def __virtual__():
'''
only load this module if the corresponding execution module is loaded
'''
if 'x509.get_pem_entry' in __salt__:
return 'x509'
else:
return False, 'Could not load x509 state: the x509 is not available'
def _get_file_args(name, **kwargs):
valid_file_args = ['user',
'group',
'mode',
'makedirs',
'dir_mode',
'backup',
'create',
'follow_symlinks',
'check_cmd']
file_args = {}
extra_args = {}
for k, v in kwargs.items():
if k in valid_file_args:
file_args[k] = v
else:
extra_args[k] = v
file_args['name'] = name
return file_args, extra_args
def _check_private_key(name, bits=2048, passphrase=None,
new=False, overwrite=False):
current_bits = 0
if os.path.isfile(name):
try:
current_bits = __salt__['x509.get_private_key_size'](
private_key=name, passphrase=passphrase)
except salt.exceptions.SaltInvocationError:
pass
except RSAError:
if not overwrite:
raise salt.exceptions.CommandExecutionError(
'The provided passphrase cannot decrypt the private key.')
return current_bits == bits and not new
def private_key_managed(name,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
new=False,
overwrite=False,
verbose=True,
**kwargs):
'''
Manage a private key's existence.
name:
Path to the private key
bits:
Key length in bits. Default 2048.
passphrase:
Passphrase for encrypting the private key.
cipher:
Cipher for encrypting the private key.
new:
Always create a new key. Defaults to False.
Combining new with :mod:`prereq <salt.states.requsities.preqreq>`, or when used as part of a
`managed_private_key` can allow key rotation whenever a new certificiate is generated.
overwrite:
Overwrite an existing private key if the provided passphrase cannot decrypt it.
verbose:
Provide visual feedback on stdout, dots while key is generated.
Default is True.
.. versionadded:: 2016.11.0
kwargs:
Any kwargs supported by file.managed are supported.
Example:
The jinja templating in this example ensures a private key is generated if the file doesn't exist
and that a new private key is generated whenever the certificate that uses it is to be renewed.
.. code-block:: jinja
/etc/pki/www.key:
x509.private_key_managed:
- bits: 4096
- new: True
{% if salt['file.file_exists']('/etc/pki/www.key') -%}
- prereq:
- x509: /etc/pki/www.crt
{%- endif %}
'''
file_args, kwargs = _get_file_args(name, **kwargs)
new_key = False
if _check_private_key(
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
file_args['contents'] = __salt__['x509.get_pem_entry'](
name, pem_type='RSA PRIVATE KEY')
else:
new_key = True
file_args['contents'] = __salt__['x509.create_private_key'](
text=True, bits=bits, passphrase=passphrase, cipher=cipher, verbose=verbose)
# Ensure the key contents are a string before passing it along
file_args['contents'] = salt.utils.stringutils.to_str(file_args['contents'])
ret = __states__['file.managed'](**file_args)
if ret['changes'] and new_key:
ret['changes'] = {'new': 'New private key generated'}
return ret
def csr_managed(name,
**kwargs):
'''
Manage a Certificate Signing Request
name:
Path to the CSR
properties:
The properties to be added to the certificate request, including items like subject, extensions
and public key. See above for valid properties.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Example:
.. code-block:: yaml
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
- DomainController: 'ASN1:UTF8String:SomeOneSomeWhere'
- ext_mapping:
'1.3.6.1.4.1.311.20.2': 'DomainController'
'''
try:
old = __salt__['x509.read_csr'](name)
except salt.exceptions.SaltInvocationError:
old = '{0} is not a valid csr.'.format(name)
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = __salt__['x509.create_csr'](text=True, **kwargs)
ret = __states__['file.managed'](**file_args)
if ret['changes']:
new = __salt__['x509.read_csr'](file_args['contents'])
if old != new:
ret['changes'] = {"Old": old, "New": new}
return ret
def certificate_managed(name,
days_remaining=90,
managed_private_key=None,
append_certs=None,
**kwargs):
'''
Manage a Certificate
name
Path to the certificate
days_remaining : 90
The minimum number of days remaining when the certificate should be
recreated. A value of 0 disables automatic renewal.
managed_private_key
Manages the private key corresponding to the certificate. All of the
arguments supported by :py:func:`x509.private_key_managed
<salt.states.x509.private_key_managed>` are supported. If `name` is not
speicified or is the same as the name of the certificate, the private
key and certificate will be written together in the same file.
append_certs:
A list of certificates to be appended to the managed file.
kwargs:
Any arguments supported by :py:func:`x509.create_certificate
<salt.modules.x509.create_certificate>` or :py:func:`file.managed
<salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Examples:
.. code-block:: yaml
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
.. code-block:: yaml
/etc/ssl/www.crt:
x509.certificate_managed:
- ca_server: pki
- signing_policy: www
- public_key: /etc/ssl/www.key
- CN: www.example.com
- days_valid: 90
- days_remaining: 30
- backup: True
'''
if 'path' in kwargs:
name = kwargs.pop('path')
file_args, kwargs = _get_file_args(name, **kwargs)
rotate_private_key = False
new_private_key = False
if managed_private_key:
private_key_args = {
'name': name,
'new': False,
'overwrite': False,
'bits': 2048,
'passphrase': None,
'cipher': 'aes_128_cbc',
'verbose': True
}
private_key_args.update(managed_private_key)
kwargs['public_key_passphrase'] = private_key_args['passphrase']
if private_key_args['new']:
rotate_private_key = True
private_key_args['new'] = False
if _check_private_key(private_key_args['name'],
bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
new=private_key_args['new'],
overwrite=private_key_args['overwrite']):
private_key = __salt__['x509.get_pem_entry'](
private_key_args['name'], pem_type='RSA PRIVATE KEY')
else:
new_private_key = True
private_key = __salt__['x509.create_private_key'](text=True, bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
cipher=private_key_args['cipher'],
verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_certificate'](certificate=name)
current_comp = copy.deepcopy(current)
if 'serial_number' not in kwargs:
current_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
current_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
current_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
current_comp.pop('Not Before')
current_comp.pop('MD5 Finger Print')
current_comp.pop('SHA1 Finger Print')
current_comp.pop('SHA-256 Finger Print')
current_notafter = current_comp.pop('Not After')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid Certificate.'.format(name)
else:
current = '{0} does not exist.'.format(name)
if 'ca_server' in kwargs and 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified if ca_server is.')
new = __salt__['x509.create_certificate'](testrun=False, text=True, **kwargs)
new = __salt__['x509.read_certificate'](certificate=new)
newcert = __salt__['x509.create_certificate'](testrun=True, **kwargs)
if isinstance(new, dict):
new_comp = copy.deepcopy(new)
if 'serial_number' not in kwargs:
new_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
new_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
new_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
new_comp.pop('Not Before')
new_comp.pop('Not After')
new_comp.pop('MD5 Finger Print')
new_comp.pop('SHA1 Finger Print')
new_comp.pop('SHA-256 Finger Print')
new_issuer_public_key = new_issuer_public_key = newcert.pop('Issuer Public Key')
else:
new_comp = new
new_certificate = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_signature'](name, new_issuer_public_key)):
certificate = __salt__['x509.get_pem_entry'](
name, pem_type='CERTIFICATE')
else:
if rotate_private_key and not new_private_key:
new_private_key = True
private_key = __salt__['x509.create_private_key'](
text=True, bits=private_key_args['bits'], verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
new_certificate = True
certificate = __salt__['x509.create_certificate'](text=True, **kwargs)
file_args['contents'] = ''
private_ret = {}
if managed_private_key:
if private_key_args['name'] == name:
file_args['contents'] = private_key
else:
private_file_args = copy.deepcopy(file_args)
unique_private_file_args, _ = _get_file_args(**private_key_args)
private_file_args.update(unique_private_file_args)
private_file_args['contents'] = private_key
private_ret = __states__['file.managed'](**private_file_args)
if not private_ret['result']:
return private_ret
file_args['contents'] += salt.utils.stringutils.to_str(certificate)
if not append_certs:
append_certs = []
for append_cert in append_certs:
file_args[
'contents'] += __salt__['x509.get_pem_entry'](append_cert, pem_type='CERTIFICATE')
file_args['show_changes'] = False
ret = __states__['file.managed'](**file_args)
if ret['changes']:
ret['changes'] = {'Certificate': ret['changes']}
else:
ret['changes'] = {}
if private_ret and private_ret['changes']:
ret['changes']['Private Key'] = private_ret['changes']
if new_private_key:
ret['changes']['Private Key'] = 'New private key generated'
if new_certificate:
ret['changes']['Certificate'] = {
'Old': current,
'New': __salt__['x509.read_certificate'](certificate=certificate)}
return ret
def crl_managed(name,
signing_private_key,
signing_private_key_passphrase=None,
signing_cert=None,
revoked=None,
days_valid=100,
digest="",
days_remaining=30,
include_expired=False,
**kwargs):
'''
Manage a Certificate Revocation List
name
Path to the certificate
signing_private_key
The private key that will be used to sign this crl. This is
usually your CA's private key.
signing_private_key_passphrase
Passphrase to decrypt the private key.
signing_cert
The certificate of the authority that will be used to sign this crl.
This is usually your CA's certificate.
revoked
A list of certificates to revoke. Must include either a serial number or a
the certificate itself. Can optionally include the revocation date and
notAfter date from the certificate. See example below for details.
days_valid : 100
The number of days the certificate should be valid for.
digest
The digest to use for signing the CRL. This has no effect on versions
of pyOpenSSL less than 0.14.
days_remaining : 30
The crl should be automatically recreated if there are less than
``days_remaining`` days until the crl expires. Set to 0 to disable
automatic renewal.
include_expired : False
If ``True``, include expired certificates in the CRL.
kwargs
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
Example:
.. code-block:: yaml
/etc/pki/ca.crl:
x509.crl_managed:
- signing_private_key: /etc/pki/myca.key
- signing_cert: /etc/pki/myca.crt
- revoked:
- compromized_Web_key:
- certificate: /etc/pki/certs/badweb.crt
- revocation_date: 2015-03-01 00:00:00
- reason: keyCompromise
- terminated_vpn_user:
- serial_number: D6:D2:DC:D8:4D:5C:C0:F4
- not_after: 2016-01-01 00:00:00
- revocation_date: 2015-02-25 00:00:00
- reason: cessationOfOperation
'''
if revoked is None:
revoked = []
revoked = _revoked_to_list(revoked)
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_crl'](crl=name)
current_comp = current.copy()
current_comp.pop('Last Update')
current_notafter = current_comp.pop('Next Update')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid CRL.'.format(name)
else:
current = '{0} does not exist.'.format(name)
new_crl = __salt__['x509.create_crl'](text=True, signing_private_key=signing_private_key,
signing_private_key_passphrase=signing_private_key_passphrase,
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid,
digest=digest, include_expired=include_expired)
new = __salt__['x509.read_crl'](crl=new_crl)
new_comp = new.copy()
new_comp.pop('Last Update')
new_comp.pop('Next Update')
file_args, kwargs = _get_file_args(name, **kwargs)
new_crl_created = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_crl'](name, signing_cert)):
file_args['contents'] = __salt__[
'x509.get_pem_entry'](name, pem_type='X509 CRL')
else:
new_crl_created = True
file_args['contents'] = new_crl
ret = __states__['file.managed'](**file_args)
if new_crl_created:
ret['changes'] = {'Old': current, 'New': __salt__[
'x509.read_crl'](crl=new_crl)}
return ret
def pem_managed(name,
text,
backup=False,
**kwargs):
'''
Manage the contents of a PEM file directly with the content in text, ensuring correct formatting.
name:
The path to the file to manage
text:
The PEM formatted text to write.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
'''
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = salt.utils.stringutils.to_str(__salt__['x509.get_pem_entry'](text=text))
return __states__['file.managed'](**file_args)
|
saltstack/salt
|
salt/states/x509.py
|
private_key_managed
|
python
|
def private_key_managed(name,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
new=False,
overwrite=False,
verbose=True,
**kwargs):
'''
Manage a private key's existence.
name:
Path to the private key
bits:
Key length in bits. Default 2048.
passphrase:
Passphrase for encrypting the private key.
cipher:
Cipher for encrypting the private key.
new:
Always create a new key. Defaults to False.
Combining new with :mod:`prereq <salt.states.requsities.preqreq>`, or when used as part of a
`managed_private_key` can allow key rotation whenever a new certificiate is generated.
overwrite:
Overwrite an existing private key if the provided passphrase cannot decrypt it.
verbose:
Provide visual feedback on stdout, dots while key is generated.
Default is True.
.. versionadded:: 2016.11.0
kwargs:
Any kwargs supported by file.managed are supported.
Example:
The jinja templating in this example ensures a private key is generated if the file doesn't exist
and that a new private key is generated whenever the certificate that uses it is to be renewed.
.. code-block:: jinja
/etc/pki/www.key:
x509.private_key_managed:
- bits: 4096
- new: True
{% if salt['file.file_exists']('/etc/pki/www.key') -%}
- prereq:
- x509: /etc/pki/www.crt
{%- endif %}
'''
file_args, kwargs = _get_file_args(name, **kwargs)
new_key = False
if _check_private_key(
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
file_args['contents'] = __salt__['x509.get_pem_entry'](
name, pem_type='RSA PRIVATE KEY')
else:
new_key = True
file_args['contents'] = __salt__['x509.create_private_key'](
text=True, bits=bits, passphrase=passphrase, cipher=cipher, verbose=verbose)
# Ensure the key contents are a string before passing it along
file_args['contents'] = salt.utils.stringutils.to_str(file_args['contents'])
ret = __states__['file.managed'](**file_args)
if ret['changes'] and new_key:
ret['changes'] = {'new': 'New private key generated'}
return ret
|
Manage a private key's existence.
name:
Path to the private key
bits:
Key length in bits. Default 2048.
passphrase:
Passphrase for encrypting the private key.
cipher:
Cipher for encrypting the private key.
new:
Always create a new key. Defaults to False.
Combining new with :mod:`prereq <salt.states.requsities.preqreq>`, or when used as part of a
`managed_private_key` can allow key rotation whenever a new certificiate is generated.
overwrite:
Overwrite an existing private key if the provided passphrase cannot decrypt it.
verbose:
Provide visual feedback on stdout, dots while key is generated.
Default is True.
.. versionadded:: 2016.11.0
kwargs:
Any kwargs supported by file.managed are supported.
Example:
The jinja templating in this example ensures a private key is generated if the file doesn't exist
and that a new private key is generated whenever the certificate that uses it is to be renewed.
.. code-block:: jinja
/etc/pki/www.key:
x509.private_key_managed:
- bits: 4096
- new: True
{% if salt['file.file_exists']('/etc/pki/www.key') -%}
- prereq:
- x509: /etc/pki/www.crt
{%- endif %}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/x509.py#L246-L320
|
[
"def _get_file_args(name, **kwargs):\n valid_file_args = ['user',\n 'group',\n 'mode',\n 'makedirs',\n 'dir_mode',\n 'backup',\n 'create',\n 'follow_symlinks',\n 'check_cmd']\n file_args = {}\n extra_args = {}\n for k, v in kwargs.items():\n if k in valid_file_args:\n file_args[k] = v\n else:\n extra_args[k] = v\n file_args['name'] = name\n return file_args, extra_args\n",
"def _check_private_key(name, bits=2048, passphrase=None,\n new=False, overwrite=False):\n current_bits = 0\n if os.path.isfile(name):\n try:\n current_bits = __salt__['x509.get_private_key_size'](\n private_key=name, passphrase=passphrase)\n except salt.exceptions.SaltInvocationError:\n pass\n except RSAError:\n if not overwrite:\n raise salt.exceptions.CommandExecutionError(\n 'The provided passphrase cannot decrypt the private key.')\n\n return current_bits == bits and not new\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 Certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
This module can enable managing a complete PKI infrastructure including creating private keys, CA's,
certificates and CRLs. It includes the ability to generate a private key on a server, and have the
corresponding public key sent to a remote CA to create a CA signed certificate. This can be done in
a secure manner, where private keys are always generated locally and never moved across the network.
Here is a simple example scenario. In this example ``ca`` is the ca server,
and ``www`` is a web server that needs a certificate signed by ``ca``.
For remote signing, peers must be permitted to remotely call the
:mod:`sign_remote_certificate <salt.modules.x509.sign_remote_certificate>` function.
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
/srv/salt/top.sls
.. code-block:: yaml
base:
'*':
- cert
'ca':
- ca
'www':
- www
This state creates the CA key, certificate and signing policy. It also publishes the certificate to
the mine where it can be easily retrieved by other minions.
/srv/salt/ca.sls
.. code-block:: yaml
salt-minion:
service.running:
- enable: True
- listen:
- file: /etc/salt/minion.d/signing_policies.conf
/etc/salt/minion.d/signing_policies.conf:
file.managed:
- source: salt://signing_policies.conf
/etc/pki:
file.directory
/etc/pki/issued_certs:
file.directory
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
- managed_private_key:
name: /etc/pki/ca.key
bits: 4096
backup: True
- require:
- file: /etc/pki
mine.send:
module.run:
- func: x509.get_pem_entries
- kwargs:
glob_path: /etc/pki/ca.crt
- onchanges:
- x509: /etc/pki/ca.crt
The signing policy defines properties that override any property requested or included in a CRL. It also
can define a restricted list of minons which are allowed to remotely invoke this signing policy.
/srv/salt/signing_policies.conf
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical keyEncipherment"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
This state will instruct all minions to trust certificates signed by our new CA.
Using jinja to strip newlines from the text avoids dealing with newlines in the rendered yaml,
and the :mod:`sign_remote_certificate <salt.states.x509.sign_remote_certificate>` state will
handle properly formatting the text before writing the output.
/srv/salt/cert.sls
.. code-block:: jinja
/usr/local/share/ca-certificates:
file.directory
/usr/local/share/ca-certificates/intca.crt:
x509.pem_managed:
- text: {{ salt['mine.get']('ca', 'x509.get_pem_entries')['ca']['/etc/pki/ca.crt']|replace('\\n', '') }}
This state creates a private key then requests a certificate signed by ca according to the www policy.
/srv/salt/www.sls
.. code-block:: yaml
/etc/pki/www.crt:
x509.certificate_managed:
- ca_server: ca
- signing_policy: www
- public_key: /etc/pki/www.key
- CN: www.example.com
- days_remaining: 30
- backup: True
- managed_private_key:
name: /etc/pki/www.key
bits: 4096
backup: True
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import datetime
import os
import re
import copy
# Import Salt Libs
import salt.exceptions
import salt.utils.stringutils
# Import 3rd-party libs
from salt.ext import six
try:
from M2Crypto.RSA import RSAError
except ImportError:
RSAError = Exception('RSA Error')
def __virtual__():
'''
only load this module if the corresponding execution module is loaded
'''
if 'x509.get_pem_entry' in __salt__:
return 'x509'
else:
return False, 'Could not load x509 state: the x509 is not available'
def _revoked_to_list(revs):
'''
Turn the mess of OrderedDicts and Lists into a list of dicts for
use in the CRL module.
'''
list_ = []
for rev in revs:
for rev_name, props in six.iteritems(
rev): # pylint: disable=unused-variable
dict_ = {}
for prop in props:
for propname, val in six.iteritems(prop):
if isinstance(val, datetime.datetime):
val = val.strftime('%Y-%m-%d %H:%M:%S')
dict_[propname] = val
list_.append(dict_)
return list_
def _get_file_args(name, **kwargs):
valid_file_args = ['user',
'group',
'mode',
'makedirs',
'dir_mode',
'backup',
'create',
'follow_symlinks',
'check_cmd']
file_args = {}
extra_args = {}
for k, v in kwargs.items():
if k in valid_file_args:
file_args[k] = v
else:
extra_args[k] = v
file_args['name'] = name
return file_args, extra_args
def _check_private_key(name, bits=2048, passphrase=None,
new=False, overwrite=False):
current_bits = 0
if os.path.isfile(name):
try:
current_bits = __salt__['x509.get_private_key_size'](
private_key=name, passphrase=passphrase)
except salt.exceptions.SaltInvocationError:
pass
except RSAError:
if not overwrite:
raise salt.exceptions.CommandExecutionError(
'The provided passphrase cannot decrypt the private key.')
return current_bits == bits and not new
def csr_managed(name,
**kwargs):
'''
Manage a Certificate Signing Request
name:
Path to the CSR
properties:
The properties to be added to the certificate request, including items like subject, extensions
and public key. See above for valid properties.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Example:
.. code-block:: yaml
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
- DomainController: 'ASN1:UTF8String:SomeOneSomeWhere'
- ext_mapping:
'1.3.6.1.4.1.311.20.2': 'DomainController'
'''
try:
old = __salt__['x509.read_csr'](name)
except salt.exceptions.SaltInvocationError:
old = '{0} is not a valid csr.'.format(name)
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = __salt__['x509.create_csr'](text=True, **kwargs)
ret = __states__['file.managed'](**file_args)
if ret['changes']:
new = __salt__['x509.read_csr'](file_args['contents'])
if old != new:
ret['changes'] = {"Old": old, "New": new}
return ret
def certificate_managed(name,
days_remaining=90,
managed_private_key=None,
append_certs=None,
**kwargs):
'''
Manage a Certificate
name
Path to the certificate
days_remaining : 90
The minimum number of days remaining when the certificate should be
recreated. A value of 0 disables automatic renewal.
managed_private_key
Manages the private key corresponding to the certificate. All of the
arguments supported by :py:func:`x509.private_key_managed
<salt.states.x509.private_key_managed>` are supported. If `name` is not
speicified or is the same as the name of the certificate, the private
key and certificate will be written together in the same file.
append_certs:
A list of certificates to be appended to the managed file.
kwargs:
Any arguments supported by :py:func:`x509.create_certificate
<salt.modules.x509.create_certificate>` or :py:func:`file.managed
<salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Examples:
.. code-block:: yaml
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
.. code-block:: yaml
/etc/ssl/www.crt:
x509.certificate_managed:
- ca_server: pki
- signing_policy: www
- public_key: /etc/ssl/www.key
- CN: www.example.com
- days_valid: 90
- days_remaining: 30
- backup: True
'''
if 'path' in kwargs:
name = kwargs.pop('path')
file_args, kwargs = _get_file_args(name, **kwargs)
rotate_private_key = False
new_private_key = False
if managed_private_key:
private_key_args = {
'name': name,
'new': False,
'overwrite': False,
'bits': 2048,
'passphrase': None,
'cipher': 'aes_128_cbc',
'verbose': True
}
private_key_args.update(managed_private_key)
kwargs['public_key_passphrase'] = private_key_args['passphrase']
if private_key_args['new']:
rotate_private_key = True
private_key_args['new'] = False
if _check_private_key(private_key_args['name'],
bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
new=private_key_args['new'],
overwrite=private_key_args['overwrite']):
private_key = __salt__['x509.get_pem_entry'](
private_key_args['name'], pem_type='RSA PRIVATE KEY')
else:
new_private_key = True
private_key = __salt__['x509.create_private_key'](text=True, bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
cipher=private_key_args['cipher'],
verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_certificate'](certificate=name)
current_comp = copy.deepcopy(current)
if 'serial_number' not in kwargs:
current_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
current_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
current_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
current_comp.pop('Not Before')
current_comp.pop('MD5 Finger Print')
current_comp.pop('SHA1 Finger Print')
current_comp.pop('SHA-256 Finger Print')
current_notafter = current_comp.pop('Not After')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid Certificate.'.format(name)
else:
current = '{0} does not exist.'.format(name)
if 'ca_server' in kwargs and 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified if ca_server is.')
new = __salt__['x509.create_certificate'](testrun=False, text=True, **kwargs)
new = __salt__['x509.read_certificate'](certificate=new)
newcert = __salt__['x509.create_certificate'](testrun=True, **kwargs)
if isinstance(new, dict):
new_comp = copy.deepcopy(new)
if 'serial_number' not in kwargs:
new_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
new_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
new_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
new_comp.pop('Not Before')
new_comp.pop('Not After')
new_comp.pop('MD5 Finger Print')
new_comp.pop('SHA1 Finger Print')
new_comp.pop('SHA-256 Finger Print')
new_issuer_public_key = new_issuer_public_key = newcert.pop('Issuer Public Key')
else:
new_comp = new
new_certificate = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_signature'](name, new_issuer_public_key)):
certificate = __salt__['x509.get_pem_entry'](
name, pem_type='CERTIFICATE')
else:
if rotate_private_key and not new_private_key:
new_private_key = True
private_key = __salt__['x509.create_private_key'](
text=True, bits=private_key_args['bits'], verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
new_certificate = True
certificate = __salt__['x509.create_certificate'](text=True, **kwargs)
file_args['contents'] = ''
private_ret = {}
if managed_private_key:
if private_key_args['name'] == name:
file_args['contents'] = private_key
else:
private_file_args = copy.deepcopy(file_args)
unique_private_file_args, _ = _get_file_args(**private_key_args)
private_file_args.update(unique_private_file_args)
private_file_args['contents'] = private_key
private_ret = __states__['file.managed'](**private_file_args)
if not private_ret['result']:
return private_ret
file_args['contents'] += salt.utils.stringutils.to_str(certificate)
if not append_certs:
append_certs = []
for append_cert in append_certs:
file_args[
'contents'] += __salt__['x509.get_pem_entry'](append_cert, pem_type='CERTIFICATE')
file_args['show_changes'] = False
ret = __states__['file.managed'](**file_args)
if ret['changes']:
ret['changes'] = {'Certificate': ret['changes']}
else:
ret['changes'] = {}
if private_ret and private_ret['changes']:
ret['changes']['Private Key'] = private_ret['changes']
if new_private_key:
ret['changes']['Private Key'] = 'New private key generated'
if new_certificate:
ret['changes']['Certificate'] = {
'Old': current,
'New': __salt__['x509.read_certificate'](certificate=certificate)}
return ret
def crl_managed(name,
signing_private_key,
signing_private_key_passphrase=None,
signing_cert=None,
revoked=None,
days_valid=100,
digest="",
days_remaining=30,
include_expired=False,
**kwargs):
'''
Manage a Certificate Revocation List
name
Path to the certificate
signing_private_key
The private key that will be used to sign this crl. This is
usually your CA's private key.
signing_private_key_passphrase
Passphrase to decrypt the private key.
signing_cert
The certificate of the authority that will be used to sign this crl.
This is usually your CA's certificate.
revoked
A list of certificates to revoke. Must include either a serial number or a
the certificate itself. Can optionally include the revocation date and
notAfter date from the certificate. See example below for details.
days_valid : 100
The number of days the certificate should be valid for.
digest
The digest to use for signing the CRL. This has no effect on versions
of pyOpenSSL less than 0.14.
days_remaining : 30
The crl should be automatically recreated if there are less than
``days_remaining`` days until the crl expires. Set to 0 to disable
automatic renewal.
include_expired : False
If ``True``, include expired certificates in the CRL.
kwargs
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
Example:
.. code-block:: yaml
/etc/pki/ca.crl:
x509.crl_managed:
- signing_private_key: /etc/pki/myca.key
- signing_cert: /etc/pki/myca.crt
- revoked:
- compromized_Web_key:
- certificate: /etc/pki/certs/badweb.crt
- revocation_date: 2015-03-01 00:00:00
- reason: keyCompromise
- terminated_vpn_user:
- serial_number: D6:D2:DC:D8:4D:5C:C0:F4
- not_after: 2016-01-01 00:00:00
- revocation_date: 2015-02-25 00:00:00
- reason: cessationOfOperation
'''
if revoked is None:
revoked = []
revoked = _revoked_to_list(revoked)
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_crl'](crl=name)
current_comp = current.copy()
current_comp.pop('Last Update')
current_notafter = current_comp.pop('Next Update')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid CRL.'.format(name)
else:
current = '{0} does not exist.'.format(name)
new_crl = __salt__['x509.create_crl'](text=True, signing_private_key=signing_private_key,
signing_private_key_passphrase=signing_private_key_passphrase,
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid,
digest=digest, include_expired=include_expired)
new = __salt__['x509.read_crl'](crl=new_crl)
new_comp = new.copy()
new_comp.pop('Last Update')
new_comp.pop('Next Update')
file_args, kwargs = _get_file_args(name, **kwargs)
new_crl_created = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_crl'](name, signing_cert)):
file_args['contents'] = __salt__[
'x509.get_pem_entry'](name, pem_type='X509 CRL')
else:
new_crl_created = True
file_args['contents'] = new_crl
ret = __states__['file.managed'](**file_args)
if new_crl_created:
ret['changes'] = {'Old': current, 'New': __salt__[
'x509.read_crl'](crl=new_crl)}
return ret
def pem_managed(name,
text,
backup=False,
**kwargs):
'''
Manage the contents of a PEM file directly with the content in text, ensuring correct formatting.
name:
The path to the file to manage
text:
The PEM formatted text to write.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
'''
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = salt.utils.stringutils.to_str(__salt__['x509.get_pem_entry'](text=text))
return __states__['file.managed'](**file_args)
|
saltstack/salt
|
salt/states/x509.py
|
csr_managed
|
python
|
def csr_managed(name,
**kwargs):
'''
Manage a Certificate Signing Request
name:
Path to the CSR
properties:
The properties to be added to the certificate request, including items like subject, extensions
and public key. See above for valid properties.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Example:
.. code-block:: yaml
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
- DomainController: 'ASN1:UTF8String:SomeOneSomeWhere'
- ext_mapping:
'1.3.6.1.4.1.311.20.2': 'DomainController'
'''
try:
old = __salt__['x509.read_csr'](name)
except salt.exceptions.SaltInvocationError:
old = '{0} is not a valid csr.'.format(name)
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = __salt__['x509.create_csr'](text=True, **kwargs)
ret = __states__['file.managed'](**file_args)
if ret['changes']:
new = __salt__['x509.read_csr'](file_args['contents'])
if old != new:
ret['changes'] = {"Old": old, "New": new}
return ret
|
Manage a Certificate Signing Request
name:
Path to the CSR
properties:
The properties to be added to the certificate request, including items like subject, extensions
and public key. See above for valid properties.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Example:
.. code-block:: yaml
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
- DomainController: 'ASN1:UTF8String:SomeOneSomeWhere'
- ext_mapping:
'1.3.6.1.4.1.311.20.2': 'DomainController'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/x509.py#L323-L385
|
[
"def _get_file_args(name, **kwargs):\n valid_file_args = ['user',\n 'group',\n 'mode',\n 'makedirs',\n 'dir_mode',\n 'backup',\n 'create',\n 'follow_symlinks',\n 'check_cmd']\n file_args = {}\n extra_args = {}\n for k, v in kwargs.items():\n if k in valid_file_args:\n file_args[k] = v\n else:\n extra_args[k] = v\n file_args['name'] = name\n return file_args, extra_args\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 Certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
This module can enable managing a complete PKI infrastructure including creating private keys, CA's,
certificates and CRLs. It includes the ability to generate a private key on a server, and have the
corresponding public key sent to a remote CA to create a CA signed certificate. This can be done in
a secure manner, where private keys are always generated locally and never moved across the network.
Here is a simple example scenario. In this example ``ca`` is the ca server,
and ``www`` is a web server that needs a certificate signed by ``ca``.
For remote signing, peers must be permitted to remotely call the
:mod:`sign_remote_certificate <salt.modules.x509.sign_remote_certificate>` function.
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
/srv/salt/top.sls
.. code-block:: yaml
base:
'*':
- cert
'ca':
- ca
'www':
- www
This state creates the CA key, certificate and signing policy. It also publishes the certificate to
the mine where it can be easily retrieved by other minions.
/srv/salt/ca.sls
.. code-block:: yaml
salt-minion:
service.running:
- enable: True
- listen:
- file: /etc/salt/minion.d/signing_policies.conf
/etc/salt/minion.d/signing_policies.conf:
file.managed:
- source: salt://signing_policies.conf
/etc/pki:
file.directory
/etc/pki/issued_certs:
file.directory
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
- managed_private_key:
name: /etc/pki/ca.key
bits: 4096
backup: True
- require:
- file: /etc/pki
mine.send:
module.run:
- func: x509.get_pem_entries
- kwargs:
glob_path: /etc/pki/ca.crt
- onchanges:
- x509: /etc/pki/ca.crt
The signing policy defines properties that override any property requested or included in a CRL. It also
can define a restricted list of minons which are allowed to remotely invoke this signing policy.
/srv/salt/signing_policies.conf
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical keyEncipherment"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
This state will instruct all minions to trust certificates signed by our new CA.
Using jinja to strip newlines from the text avoids dealing with newlines in the rendered yaml,
and the :mod:`sign_remote_certificate <salt.states.x509.sign_remote_certificate>` state will
handle properly formatting the text before writing the output.
/srv/salt/cert.sls
.. code-block:: jinja
/usr/local/share/ca-certificates:
file.directory
/usr/local/share/ca-certificates/intca.crt:
x509.pem_managed:
- text: {{ salt['mine.get']('ca', 'x509.get_pem_entries')['ca']['/etc/pki/ca.crt']|replace('\\n', '') }}
This state creates a private key then requests a certificate signed by ca according to the www policy.
/srv/salt/www.sls
.. code-block:: yaml
/etc/pki/www.crt:
x509.certificate_managed:
- ca_server: ca
- signing_policy: www
- public_key: /etc/pki/www.key
- CN: www.example.com
- days_remaining: 30
- backup: True
- managed_private_key:
name: /etc/pki/www.key
bits: 4096
backup: True
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import datetime
import os
import re
import copy
# Import Salt Libs
import salt.exceptions
import salt.utils.stringutils
# Import 3rd-party libs
from salt.ext import six
try:
from M2Crypto.RSA import RSAError
except ImportError:
RSAError = Exception('RSA Error')
def __virtual__():
'''
only load this module if the corresponding execution module is loaded
'''
if 'x509.get_pem_entry' in __salt__:
return 'x509'
else:
return False, 'Could not load x509 state: the x509 is not available'
def _revoked_to_list(revs):
'''
Turn the mess of OrderedDicts and Lists into a list of dicts for
use in the CRL module.
'''
list_ = []
for rev in revs:
for rev_name, props in six.iteritems(
rev): # pylint: disable=unused-variable
dict_ = {}
for prop in props:
for propname, val in six.iteritems(prop):
if isinstance(val, datetime.datetime):
val = val.strftime('%Y-%m-%d %H:%M:%S')
dict_[propname] = val
list_.append(dict_)
return list_
def _get_file_args(name, **kwargs):
valid_file_args = ['user',
'group',
'mode',
'makedirs',
'dir_mode',
'backup',
'create',
'follow_symlinks',
'check_cmd']
file_args = {}
extra_args = {}
for k, v in kwargs.items():
if k in valid_file_args:
file_args[k] = v
else:
extra_args[k] = v
file_args['name'] = name
return file_args, extra_args
def _check_private_key(name, bits=2048, passphrase=None,
new=False, overwrite=False):
current_bits = 0
if os.path.isfile(name):
try:
current_bits = __salt__['x509.get_private_key_size'](
private_key=name, passphrase=passphrase)
except salt.exceptions.SaltInvocationError:
pass
except RSAError:
if not overwrite:
raise salt.exceptions.CommandExecutionError(
'The provided passphrase cannot decrypt the private key.')
return current_bits == bits and not new
def private_key_managed(name,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
new=False,
overwrite=False,
verbose=True,
**kwargs):
'''
Manage a private key's existence.
name:
Path to the private key
bits:
Key length in bits. Default 2048.
passphrase:
Passphrase for encrypting the private key.
cipher:
Cipher for encrypting the private key.
new:
Always create a new key. Defaults to False.
Combining new with :mod:`prereq <salt.states.requsities.preqreq>`, or when used as part of a
`managed_private_key` can allow key rotation whenever a new certificiate is generated.
overwrite:
Overwrite an existing private key if the provided passphrase cannot decrypt it.
verbose:
Provide visual feedback on stdout, dots while key is generated.
Default is True.
.. versionadded:: 2016.11.0
kwargs:
Any kwargs supported by file.managed are supported.
Example:
The jinja templating in this example ensures a private key is generated if the file doesn't exist
and that a new private key is generated whenever the certificate that uses it is to be renewed.
.. code-block:: jinja
/etc/pki/www.key:
x509.private_key_managed:
- bits: 4096
- new: True
{% if salt['file.file_exists']('/etc/pki/www.key') -%}
- prereq:
- x509: /etc/pki/www.crt
{%- endif %}
'''
file_args, kwargs = _get_file_args(name, **kwargs)
new_key = False
if _check_private_key(
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
file_args['contents'] = __salt__['x509.get_pem_entry'](
name, pem_type='RSA PRIVATE KEY')
else:
new_key = True
file_args['contents'] = __salt__['x509.create_private_key'](
text=True, bits=bits, passphrase=passphrase, cipher=cipher, verbose=verbose)
# Ensure the key contents are a string before passing it along
file_args['contents'] = salt.utils.stringutils.to_str(file_args['contents'])
ret = __states__['file.managed'](**file_args)
if ret['changes'] and new_key:
ret['changes'] = {'new': 'New private key generated'}
return ret
def certificate_managed(name,
days_remaining=90,
managed_private_key=None,
append_certs=None,
**kwargs):
'''
Manage a Certificate
name
Path to the certificate
days_remaining : 90
The minimum number of days remaining when the certificate should be
recreated. A value of 0 disables automatic renewal.
managed_private_key
Manages the private key corresponding to the certificate. All of the
arguments supported by :py:func:`x509.private_key_managed
<salt.states.x509.private_key_managed>` are supported. If `name` is not
speicified or is the same as the name of the certificate, the private
key and certificate will be written together in the same file.
append_certs:
A list of certificates to be appended to the managed file.
kwargs:
Any arguments supported by :py:func:`x509.create_certificate
<salt.modules.x509.create_certificate>` or :py:func:`file.managed
<salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Examples:
.. code-block:: yaml
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
.. code-block:: yaml
/etc/ssl/www.crt:
x509.certificate_managed:
- ca_server: pki
- signing_policy: www
- public_key: /etc/ssl/www.key
- CN: www.example.com
- days_valid: 90
- days_remaining: 30
- backup: True
'''
if 'path' in kwargs:
name = kwargs.pop('path')
file_args, kwargs = _get_file_args(name, **kwargs)
rotate_private_key = False
new_private_key = False
if managed_private_key:
private_key_args = {
'name': name,
'new': False,
'overwrite': False,
'bits': 2048,
'passphrase': None,
'cipher': 'aes_128_cbc',
'verbose': True
}
private_key_args.update(managed_private_key)
kwargs['public_key_passphrase'] = private_key_args['passphrase']
if private_key_args['new']:
rotate_private_key = True
private_key_args['new'] = False
if _check_private_key(private_key_args['name'],
bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
new=private_key_args['new'],
overwrite=private_key_args['overwrite']):
private_key = __salt__['x509.get_pem_entry'](
private_key_args['name'], pem_type='RSA PRIVATE KEY')
else:
new_private_key = True
private_key = __salt__['x509.create_private_key'](text=True, bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
cipher=private_key_args['cipher'],
verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_certificate'](certificate=name)
current_comp = copy.deepcopy(current)
if 'serial_number' not in kwargs:
current_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
current_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
current_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
current_comp.pop('Not Before')
current_comp.pop('MD5 Finger Print')
current_comp.pop('SHA1 Finger Print')
current_comp.pop('SHA-256 Finger Print')
current_notafter = current_comp.pop('Not After')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid Certificate.'.format(name)
else:
current = '{0} does not exist.'.format(name)
if 'ca_server' in kwargs and 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified if ca_server is.')
new = __salt__['x509.create_certificate'](testrun=False, text=True, **kwargs)
new = __salt__['x509.read_certificate'](certificate=new)
newcert = __salt__['x509.create_certificate'](testrun=True, **kwargs)
if isinstance(new, dict):
new_comp = copy.deepcopy(new)
if 'serial_number' not in kwargs:
new_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
new_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
new_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
new_comp.pop('Not Before')
new_comp.pop('Not After')
new_comp.pop('MD5 Finger Print')
new_comp.pop('SHA1 Finger Print')
new_comp.pop('SHA-256 Finger Print')
new_issuer_public_key = new_issuer_public_key = newcert.pop('Issuer Public Key')
else:
new_comp = new
new_certificate = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_signature'](name, new_issuer_public_key)):
certificate = __salt__['x509.get_pem_entry'](
name, pem_type='CERTIFICATE')
else:
if rotate_private_key and not new_private_key:
new_private_key = True
private_key = __salt__['x509.create_private_key'](
text=True, bits=private_key_args['bits'], verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
new_certificate = True
certificate = __salt__['x509.create_certificate'](text=True, **kwargs)
file_args['contents'] = ''
private_ret = {}
if managed_private_key:
if private_key_args['name'] == name:
file_args['contents'] = private_key
else:
private_file_args = copy.deepcopy(file_args)
unique_private_file_args, _ = _get_file_args(**private_key_args)
private_file_args.update(unique_private_file_args)
private_file_args['contents'] = private_key
private_ret = __states__['file.managed'](**private_file_args)
if not private_ret['result']:
return private_ret
file_args['contents'] += salt.utils.stringutils.to_str(certificate)
if not append_certs:
append_certs = []
for append_cert in append_certs:
file_args[
'contents'] += __salt__['x509.get_pem_entry'](append_cert, pem_type='CERTIFICATE')
file_args['show_changes'] = False
ret = __states__['file.managed'](**file_args)
if ret['changes']:
ret['changes'] = {'Certificate': ret['changes']}
else:
ret['changes'] = {}
if private_ret and private_ret['changes']:
ret['changes']['Private Key'] = private_ret['changes']
if new_private_key:
ret['changes']['Private Key'] = 'New private key generated'
if new_certificate:
ret['changes']['Certificate'] = {
'Old': current,
'New': __salt__['x509.read_certificate'](certificate=certificate)}
return ret
def crl_managed(name,
signing_private_key,
signing_private_key_passphrase=None,
signing_cert=None,
revoked=None,
days_valid=100,
digest="",
days_remaining=30,
include_expired=False,
**kwargs):
'''
Manage a Certificate Revocation List
name
Path to the certificate
signing_private_key
The private key that will be used to sign this crl. This is
usually your CA's private key.
signing_private_key_passphrase
Passphrase to decrypt the private key.
signing_cert
The certificate of the authority that will be used to sign this crl.
This is usually your CA's certificate.
revoked
A list of certificates to revoke. Must include either a serial number or a
the certificate itself. Can optionally include the revocation date and
notAfter date from the certificate. See example below for details.
days_valid : 100
The number of days the certificate should be valid for.
digest
The digest to use for signing the CRL. This has no effect on versions
of pyOpenSSL less than 0.14.
days_remaining : 30
The crl should be automatically recreated if there are less than
``days_remaining`` days until the crl expires. Set to 0 to disable
automatic renewal.
include_expired : False
If ``True``, include expired certificates in the CRL.
kwargs
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
Example:
.. code-block:: yaml
/etc/pki/ca.crl:
x509.crl_managed:
- signing_private_key: /etc/pki/myca.key
- signing_cert: /etc/pki/myca.crt
- revoked:
- compromized_Web_key:
- certificate: /etc/pki/certs/badweb.crt
- revocation_date: 2015-03-01 00:00:00
- reason: keyCompromise
- terminated_vpn_user:
- serial_number: D6:D2:DC:D8:4D:5C:C0:F4
- not_after: 2016-01-01 00:00:00
- revocation_date: 2015-02-25 00:00:00
- reason: cessationOfOperation
'''
if revoked is None:
revoked = []
revoked = _revoked_to_list(revoked)
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_crl'](crl=name)
current_comp = current.copy()
current_comp.pop('Last Update')
current_notafter = current_comp.pop('Next Update')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid CRL.'.format(name)
else:
current = '{0} does not exist.'.format(name)
new_crl = __salt__['x509.create_crl'](text=True, signing_private_key=signing_private_key,
signing_private_key_passphrase=signing_private_key_passphrase,
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid,
digest=digest, include_expired=include_expired)
new = __salt__['x509.read_crl'](crl=new_crl)
new_comp = new.copy()
new_comp.pop('Last Update')
new_comp.pop('Next Update')
file_args, kwargs = _get_file_args(name, **kwargs)
new_crl_created = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_crl'](name, signing_cert)):
file_args['contents'] = __salt__[
'x509.get_pem_entry'](name, pem_type='X509 CRL')
else:
new_crl_created = True
file_args['contents'] = new_crl
ret = __states__['file.managed'](**file_args)
if new_crl_created:
ret['changes'] = {'Old': current, 'New': __salt__[
'x509.read_crl'](crl=new_crl)}
return ret
def pem_managed(name,
text,
backup=False,
**kwargs):
'''
Manage the contents of a PEM file directly with the content in text, ensuring correct formatting.
name:
The path to the file to manage
text:
The PEM formatted text to write.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
'''
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = salt.utils.stringutils.to_str(__salt__['x509.get_pem_entry'](text=text))
return __states__['file.managed'](**file_args)
|
saltstack/salt
|
salt/states/x509.py
|
certificate_managed
|
python
|
def certificate_managed(name,
days_remaining=90,
managed_private_key=None,
append_certs=None,
**kwargs):
'''
Manage a Certificate
name
Path to the certificate
days_remaining : 90
The minimum number of days remaining when the certificate should be
recreated. A value of 0 disables automatic renewal.
managed_private_key
Manages the private key corresponding to the certificate. All of the
arguments supported by :py:func:`x509.private_key_managed
<salt.states.x509.private_key_managed>` are supported. If `name` is not
speicified or is the same as the name of the certificate, the private
key and certificate will be written together in the same file.
append_certs:
A list of certificates to be appended to the managed file.
kwargs:
Any arguments supported by :py:func:`x509.create_certificate
<salt.modules.x509.create_certificate>` or :py:func:`file.managed
<salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Examples:
.. code-block:: yaml
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
.. code-block:: yaml
/etc/ssl/www.crt:
x509.certificate_managed:
- ca_server: pki
- signing_policy: www
- public_key: /etc/ssl/www.key
- CN: www.example.com
- days_valid: 90
- days_remaining: 30
- backup: True
'''
if 'path' in kwargs:
name = kwargs.pop('path')
file_args, kwargs = _get_file_args(name, **kwargs)
rotate_private_key = False
new_private_key = False
if managed_private_key:
private_key_args = {
'name': name,
'new': False,
'overwrite': False,
'bits': 2048,
'passphrase': None,
'cipher': 'aes_128_cbc',
'verbose': True
}
private_key_args.update(managed_private_key)
kwargs['public_key_passphrase'] = private_key_args['passphrase']
if private_key_args['new']:
rotate_private_key = True
private_key_args['new'] = False
if _check_private_key(private_key_args['name'],
bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
new=private_key_args['new'],
overwrite=private_key_args['overwrite']):
private_key = __salt__['x509.get_pem_entry'](
private_key_args['name'], pem_type='RSA PRIVATE KEY')
else:
new_private_key = True
private_key = __salt__['x509.create_private_key'](text=True, bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
cipher=private_key_args['cipher'],
verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_certificate'](certificate=name)
current_comp = copy.deepcopy(current)
if 'serial_number' not in kwargs:
current_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
current_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
current_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
current_comp.pop('Not Before')
current_comp.pop('MD5 Finger Print')
current_comp.pop('SHA1 Finger Print')
current_comp.pop('SHA-256 Finger Print')
current_notafter = current_comp.pop('Not After')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid Certificate.'.format(name)
else:
current = '{0} does not exist.'.format(name)
if 'ca_server' in kwargs and 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified if ca_server is.')
new = __salt__['x509.create_certificate'](testrun=False, text=True, **kwargs)
new = __salt__['x509.read_certificate'](certificate=new)
newcert = __salt__['x509.create_certificate'](testrun=True, **kwargs)
if isinstance(new, dict):
new_comp = copy.deepcopy(new)
if 'serial_number' not in kwargs:
new_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
new_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
new_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
new_comp.pop('Not Before')
new_comp.pop('Not After')
new_comp.pop('MD5 Finger Print')
new_comp.pop('SHA1 Finger Print')
new_comp.pop('SHA-256 Finger Print')
new_issuer_public_key = new_issuer_public_key = newcert.pop('Issuer Public Key')
else:
new_comp = new
new_certificate = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_signature'](name, new_issuer_public_key)):
certificate = __salt__['x509.get_pem_entry'](
name, pem_type='CERTIFICATE')
else:
if rotate_private_key and not new_private_key:
new_private_key = True
private_key = __salt__['x509.create_private_key'](
text=True, bits=private_key_args['bits'], verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
new_certificate = True
certificate = __salt__['x509.create_certificate'](text=True, **kwargs)
file_args['contents'] = ''
private_ret = {}
if managed_private_key:
if private_key_args['name'] == name:
file_args['contents'] = private_key
else:
private_file_args = copy.deepcopy(file_args)
unique_private_file_args, _ = _get_file_args(**private_key_args)
private_file_args.update(unique_private_file_args)
private_file_args['contents'] = private_key
private_ret = __states__['file.managed'](**private_file_args)
if not private_ret['result']:
return private_ret
file_args['contents'] += salt.utils.stringutils.to_str(certificate)
if not append_certs:
append_certs = []
for append_cert in append_certs:
file_args[
'contents'] += __salt__['x509.get_pem_entry'](append_cert, pem_type='CERTIFICATE')
file_args['show_changes'] = False
ret = __states__['file.managed'](**file_args)
if ret['changes']:
ret['changes'] = {'Certificate': ret['changes']}
else:
ret['changes'] = {}
if private_ret and private_ret['changes']:
ret['changes']['Private Key'] = private_ret['changes']
if new_private_key:
ret['changes']['Private Key'] = 'New private key generated'
if new_certificate:
ret['changes']['Certificate'] = {
'Old': current,
'New': __salt__['x509.read_certificate'](certificate=certificate)}
return ret
|
Manage a Certificate
name
Path to the certificate
days_remaining : 90
The minimum number of days remaining when the certificate should be
recreated. A value of 0 disables automatic renewal.
managed_private_key
Manages the private key corresponding to the certificate. All of the
arguments supported by :py:func:`x509.private_key_managed
<salt.states.x509.private_key_managed>` are supported. If `name` is not
speicified or is the same as the name of the certificate, the private
key and certificate will be written together in the same file.
append_certs:
A list of certificates to be appended to the managed file.
kwargs:
Any arguments supported by :py:func:`x509.create_certificate
<salt.modules.x509.create_certificate>` or :py:func:`file.managed
<salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Examples:
.. code-block:: yaml
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
.. code-block:: yaml
/etc/ssl/www.crt:
x509.certificate_managed:
- ca_server: pki
- signing_policy: www
- public_key: /etc/ssl/www.key
- CN: www.example.com
- days_valid: 90
- days_remaining: 30
- backup: True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/x509.py#L388-L610
|
[
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def _get_file_args(name, **kwargs):\n valid_file_args = ['user',\n 'group',\n 'mode',\n 'makedirs',\n 'dir_mode',\n 'backup',\n 'create',\n 'follow_symlinks',\n 'check_cmd']\n file_args = {}\n extra_args = {}\n for k, v in kwargs.items():\n if k in valid_file_args:\n file_args[k] = v\n else:\n extra_args[k] = v\n file_args['name'] = name\n return file_args, extra_args\n",
"def _check_private_key(name, bits=2048, passphrase=None,\n new=False, overwrite=False):\n current_bits = 0\n if os.path.isfile(name):\n try:\n current_bits = __salt__['x509.get_private_key_size'](\n private_key=name, passphrase=passphrase)\n except salt.exceptions.SaltInvocationError:\n pass\n except RSAError:\n if not overwrite:\n raise salt.exceptions.CommandExecutionError(\n 'The provided passphrase cannot decrypt the private key.')\n\n return current_bits == bits and not new\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 Certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
This module can enable managing a complete PKI infrastructure including creating private keys, CA's,
certificates and CRLs. It includes the ability to generate a private key on a server, and have the
corresponding public key sent to a remote CA to create a CA signed certificate. This can be done in
a secure manner, where private keys are always generated locally and never moved across the network.
Here is a simple example scenario. In this example ``ca`` is the ca server,
and ``www`` is a web server that needs a certificate signed by ``ca``.
For remote signing, peers must be permitted to remotely call the
:mod:`sign_remote_certificate <salt.modules.x509.sign_remote_certificate>` function.
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
/srv/salt/top.sls
.. code-block:: yaml
base:
'*':
- cert
'ca':
- ca
'www':
- www
This state creates the CA key, certificate and signing policy. It also publishes the certificate to
the mine where it can be easily retrieved by other minions.
/srv/salt/ca.sls
.. code-block:: yaml
salt-minion:
service.running:
- enable: True
- listen:
- file: /etc/salt/minion.d/signing_policies.conf
/etc/salt/minion.d/signing_policies.conf:
file.managed:
- source: salt://signing_policies.conf
/etc/pki:
file.directory
/etc/pki/issued_certs:
file.directory
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
- managed_private_key:
name: /etc/pki/ca.key
bits: 4096
backup: True
- require:
- file: /etc/pki
mine.send:
module.run:
- func: x509.get_pem_entries
- kwargs:
glob_path: /etc/pki/ca.crt
- onchanges:
- x509: /etc/pki/ca.crt
The signing policy defines properties that override any property requested or included in a CRL. It also
can define a restricted list of minons which are allowed to remotely invoke this signing policy.
/srv/salt/signing_policies.conf
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical keyEncipherment"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
This state will instruct all minions to trust certificates signed by our new CA.
Using jinja to strip newlines from the text avoids dealing with newlines in the rendered yaml,
and the :mod:`sign_remote_certificate <salt.states.x509.sign_remote_certificate>` state will
handle properly formatting the text before writing the output.
/srv/salt/cert.sls
.. code-block:: jinja
/usr/local/share/ca-certificates:
file.directory
/usr/local/share/ca-certificates/intca.crt:
x509.pem_managed:
- text: {{ salt['mine.get']('ca', 'x509.get_pem_entries')['ca']['/etc/pki/ca.crt']|replace('\\n', '') }}
This state creates a private key then requests a certificate signed by ca according to the www policy.
/srv/salt/www.sls
.. code-block:: yaml
/etc/pki/www.crt:
x509.certificate_managed:
- ca_server: ca
- signing_policy: www
- public_key: /etc/pki/www.key
- CN: www.example.com
- days_remaining: 30
- backup: True
- managed_private_key:
name: /etc/pki/www.key
bits: 4096
backup: True
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import datetime
import os
import re
import copy
# Import Salt Libs
import salt.exceptions
import salt.utils.stringutils
# Import 3rd-party libs
from salt.ext import six
try:
from M2Crypto.RSA import RSAError
except ImportError:
RSAError = Exception('RSA Error')
def __virtual__():
'''
only load this module if the corresponding execution module is loaded
'''
if 'x509.get_pem_entry' in __salt__:
return 'x509'
else:
return False, 'Could not load x509 state: the x509 is not available'
def _revoked_to_list(revs):
'''
Turn the mess of OrderedDicts and Lists into a list of dicts for
use in the CRL module.
'''
list_ = []
for rev in revs:
for rev_name, props in six.iteritems(
rev): # pylint: disable=unused-variable
dict_ = {}
for prop in props:
for propname, val in six.iteritems(prop):
if isinstance(val, datetime.datetime):
val = val.strftime('%Y-%m-%d %H:%M:%S')
dict_[propname] = val
list_.append(dict_)
return list_
def _get_file_args(name, **kwargs):
valid_file_args = ['user',
'group',
'mode',
'makedirs',
'dir_mode',
'backup',
'create',
'follow_symlinks',
'check_cmd']
file_args = {}
extra_args = {}
for k, v in kwargs.items():
if k in valid_file_args:
file_args[k] = v
else:
extra_args[k] = v
file_args['name'] = name
return file_args, extra_args
def _check_private_key(name, bits=2048, passphrase=None,
new=False, overwrite=False):
current_bits = 0
if os.path.isfile(name):
try:
current_bits = __salt__['x509.get_private_key_size'](
private_key=name, passphrase=passphrase)
except salt.exceptions.SaltInvocationError:
pass
except RSAError:
if not overwrite:
raise salt.exceptions.CommandExecutionError(
'The provided passphrase cannot decrypt the private key.')
return current_bits == bits and not new
def private_key_managed(name,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
new=False,
overwrite=False,
verbose=True,
**kwargs):
'''
Manage a private key's existence.
name:
Path to the private key
bits:
Key length in bits. Default 2048.
passphrase:
Passphrase for encrypting the private key.
cipher:
Cipher for encrypting the private key.
new:
Always create a new key. Defaults to False.
Combining new with :mod:`prereq <salt.states.requsities.preqreq>`, or when used as part of a
`managed_private_key` can allow key rotation whenever a new certificiate is generated.
overwrite:
Overwrite an existing private key if the provided passphrase cannot decrypt it.
verbose:
Provide visual feedback on stdout, dots while key is generated.
Default is True.
.. versionadded:: 2016.11.0
kwargs:
Any kwargs supported by file.managed are supported.
Example:
The jinja templating in this example ensures a private key is generated if the file doesn't exist
and that a new private key is generated whenever the certificate that uses it is to be renewed.
.. code-block:: jinja
/etc/pki/www.key:
x509.private_key_managed:
- bits: 4096
- new: True
{% if salt['file.file_exists']('/etc/pki/www.key') -%}
- prereq:
- x509: /etc/pki/www.crt
{%- endif %}
'''
file_args, kwargs = _get_file_args(name, **kwargs)
new_key = False
if _check_private_key(
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
file_args['contents'] = __salt__['x509.get_pem_entry'](
name, pem_type='RSA PRIVATE KEY')
else:
new_key = True
file_args['contents'] = __salt__['x509.create_private_key'](
text=True, bits=bits, passphrase=passphrase, cipher=cipher, verbose=verbose)
# Ensure the key contents are a string before passing it along
file_args['contents'] = salt.utils.stringutils.to_str(file_args['contents'])
ret = __states__['file.managed'](**file_args)
if ret['changes'] and new_key:
ret['changes'] = {'new': 'New private key generated'}
return ret
def csr_managed(name,
**kwargs):
'''
Manage a Certificate Signing Request
name:
Path to the CSR
properties:
The properties to be added to the certificate request, including items like subject, extensions
and public key. See above for valid properties.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Example:
.. code-block:: yaml
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
- DomainController: 'ASN1:UTF8String:SomeOneSomeWhere'
- ext_mapping:
'1.3.6.1.4.1.311.20.2': 'DomainController'
'''
try:
old = __salt__['x509.read_csr'](name)
except salt.exceptions.SaltInvocationError:
old = '{0} is not a valid csr.'.format(name)
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = __salt__['x509.create_csr'](text=True, **kwargs)
ret = __states__['file.managed'](**file_args)
if ret['changes']:
new = __salt__['x509.read_csr'](file_args['contents'])
if old != new:
ret['changes'] = {"Old": old, "New": new}
return ret
def crl_managed(name,
signing_private_key,
signing_private_key_passphrase=None,
signing_cert=None,
revoked=None,
days_valid=100,
digest="",
days_remaining=30,
include_expired=False,
**kwargs):
'''
Manage a Certificate Revocation List
name
Path to the certificate
signing_private_key
The private key that will be used to sign this crl. This is
usually your CA's private key.
signing_private_key_passphrase
Passphrase to decrypt the private key.
signing_cert
The certificate of the authority that will be used to sign this crl.
This is usually your CA's certificate.
revoked
A list of certificates to revoke. Must include either a serial number or a
the certificate itself. Can optionally include the revocation date and
notAfter date from the certificate. See example below for details.
days_valid : 100
The number of days the certificate should be valid for.
digest
The digest to use for signing the CRL. This has no effect on versions
of pyOpenSSL less than 0.14.
days_remaining : 30
The crl should be automatically recreated if there are less than
``days_remaining`` days until the crl expires. Set to 0 to disable
automatic renewal.
include_expired : False
If ``True``, include expired certificates in the CRL.
kwargs
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
Example:
.. code-block:: yaml
/etc/pki/ca.crl:
x509.crl_managed:
- signing_private_key: /etc/pki/myca.key
- signing_cert: /etc/pki/myca.crt
- revoked:
- compromized_Web_key:
- certificate: /etc/pki/certs/badweb.crt
- revocation_date: 2015-03-01 00:00:00
- reason: keyCompromise
- terminated_vpn_user:
- serial_number: D6:D2:DC:D8:4D:5C:C0:F4
- not_after: 2016-01-01 00:00:00
- revocation_date: 2015-02-25 00:00:00
- reason: cessationOfOperation
'''
if revoked is None:
revoked = []
revoked = _revoked_to_list(revoked)
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_crl'](crl=name)
current_comp = current.copy()
current_comp.pop('Last Update')
current_notafter = current_comp.pop('Next Update')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid CRL.'.format(name)
else:
current = '{0} does not exist.'.format(name)
new_crl = __salt__['x509.create_crl'](text=True, signing_private_key=signing_private_key,
signing_private_key_passphrase=signing_private_key_passphrase,
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid,
digest=digest, include_expired=include_expired)
new = __salt__['x509.read_crl'](crl=new_crl)
new_comp = new.copy()
new_comp.pop('Last Update')
new_comp.pop('Next Update')
file_args, kwargs = _get_file_args(name, **kwargs)
new_crl_created = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_crl'](name, signing_cert)):
file_args['contents'] = __salt__[
'x509.get_pem_entry'](name, pem_type='X509 CRL')
else:
new_crl_created = True
file_args['contents'] = new_crl
ret = __states__['file.managed'](**file_args)
if new_crl_created:
ret['changes'] = {'Old': current, 'New': __salt__[
'x509.read_crl'](crl=new_crl)}
return ret
def pem_managed(name,
text,
backup=False,
**kwargs):
'''
Manage the contents of a PEM file directly with the content in text, ensuring correct formatting.
name:
The path to the file to manage
text:
The PEM formatted text to write.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
'''
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = salt.utils.stringutils.to_str(__salt__['x509.get_pem_entry'](text=text))
return __states__['file.managed'](**file_args)
|
saltstack/salt
|
salt/states/x509.py
|
crl_managed
|
python
|
def crl_managed(name,
signing_private_key,
signing_private_key_passphrase=None,
signing_cert=None,
revoked=None,
days_valid=100,
digest="",
days_remaining=30,
include_expired=False,
**kwargs):
'''
Manage a Certificate Revocation List
name
Path to the certificate
signing_private_key
The private key that will be used to sign this crl. This is
usually your CA's private key.
signing_private_key_passphrase
Passphrase to decrypt the private key.
signing_cert
The certificate of the authority that will be used to sign this crl.
This is usually your CA's certificate.
revoked
A list of certificates to revoke. Must include either a serial number or a
the certificate itself. Can optionally include the revocation date and
notAfter date from the certificate. See example below for details.
days_valid : 100
The number of days the certificate should be valid for.
digest
The digest to use for signing the CRL. This has no effect on versions
of pyOpenSSL less than 0.14.
days_remaining : 30
The crl should be automatically recreated if there are less than
``days_remaining`` days until the crl expires. Set to 0 to disable
automatic renewal.
include_expired : False
If ``True``, include expired certificates in the CRL.
kwargs
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
Example:
.. code-block:: yaml
/etc/pki/ca.crl:
x509.crl_managed:
- signing_private_key: /etc/pki/myca.key
- signing_cert: /etc/pki/myca.crt
- revoked:
- compromized_Web_key:
- certificate: /etc/pki/certs/badweb.crt
- revocation_date: 2015-03-01 00:00:00
- reason: keyCompromise
- terminated_vpn_user:
- serial_number: D6:D2:DC:D8:4D:5C:C0:F4
- not_after: 2016-01-01 00:00:00
- revocation_date: 2015-02-25 00:00:00
- reason: cessationOfOperation
'''
if revoked is None:
revoked = []
revoked = _revoked_to_list(revoked)
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_crl'](crl=name)
current_comp = current.copy()
current_comp.pop('Last Update')
current_notafter = current_comp.pop('Next Update')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid CRL.'.format(name)
else:
current = '{0} does not exist.'.format(name)
new_crl = __salt__['x509.create_crl'](text=True, signing_private_key=signing_private_key,
signing_private_key_passphrase=signing_private_key_passphrase,
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid,
digest=digest, include_expired=include_expired)
new = __salt__['x509.read_crl'](crl=new_crl)
new_comp = new.copy()
new_comp.pop('Last Update')
new_comp.pop('Next Update')
file_args, kwargs = _get_file_args(name, **kwargs)
new_crl_created = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_crl'](name, signing_cert)):
file_args['contents'] = __salt__[
'x509.get_pem_entry'](name, pem_type='X509 CRL')
else:
new_crl_created = True
file_args['contents'] = new_crl
ret = __states__['file.managed'](**file_args)
if new_crl_created:
ret['changes'] = {'Old': current, 'New': __salt__[
'x509.read_crl'](crl=new_crl)}
return ret
|
Manage a Certificate Revocation List
name
Path to the certificate
signing_private_key
The private key that will be used to sign this crl. This is
usually your CA's private key.
signing_private_key_passphrase
Passphrase to decrypt the private key.
signing_cert
The certificate of the authority that will be used to sign this crl.
This is usually your CA's certificate.
revoked
A list of certificates to revoke. Must include either a serial number or a
the certificate itself. Can optionally include the revocation date and
notAfter date from the certificate. See example below for details.
days_valid : 100
The number of days the certificate should be valid for.
digest
The digest to use for signing the CRL. This has no effect on versions
of pyOpenSSL less than 0.14.
days_remaining : 30
The crl should be automatically recreated if there are less than
``days_remaining`` days until the crl expires. Set to 0 to disable
automatic renewal.
include_expired : False
If ``True``, include expired certificates in the CRL.
kwargs
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
Example:
.. code-block:: yaml
/etc/pki/ca.crl:
x509.crl_managed:
- signing_private_key: /etc/pki/myca.key
- signing_cert: /etc/pki/myca.crt
- revoked:
- compromized_Web_key:
- certificate: /etc/pki/certs/badweb.crt
- revocation_date: 2015-03-01 00:00:00
- reason: keyCompromise
- terminated_vpn_user:
- serial_number: D6:D2:DC:D8:4D:5C:C0:F4
- not_after: 2016-01-01 00:00:00
- revocation_date: 2015-02-25 00:00:00
- reason: cessationOfOperation
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/x509.py#L613-L731
|
[
"def _revoked_to_list(revs):\n '''\n Turn the mess of OrderedDicts and Lists into a list of dicts for\n use in the CRL module.\n '''\n list_ = []\n\n for rev in revs:\n for rev_name, props in six.iteritems(\n rev): # pylint: disable=unused-variable\n dict_ = {}\n for prop in props:\n for propname, val in six.iteritems(prop):\n if isinstance(val, datetime.datetime):\n val = val.strftime('%Y-%m-%d %H:%M:%S')\n dict_[propname] = val\n list_.append(dict_)\n\n return list_\n",
"def _get_file_args(name, **kwargs):\n valid_file_args = ['user',\n 'group',\n 'mode',\n 'makedirs',\n 'dir_mode',\n 'backup',\n 'create',\n 'follow_symlinks',\n 'check_cmd']\n file_args = {}\n extra_args = {}\n for k, v in kwargs.items():\n if k in valid_file_args:\n file_args[k] = v\n else:\n extra_args[k] = v\n file_args['name'] = name\n return file_args, extra_args\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 Certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
This module can enable managing a complete PKI infrastructure including creating private keys, CA's,
certificates and CRLs. It includes the ability to generate a private key on a server, and have the
corresponding public key sent to a remote CA to create a CA signed certificate. This can be done in
a secure manner, where private keys are always generated locally and never moved across the network.
Here is a simple example scenario. In this example ``ca`` is the ca server,
and ``www`` is a web server that needs a certificate signed by ``ca``.
For remote signing, peers must be permitted to remotely call the
:mod:`sign_remote_certificate <salt.modules.x509.sign_remote_certificate>` function.
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
/srv/salt/top.sls
.. code-block:: yaml
base:
'*':
- cert
'ca':
- ca
'www':
- www
This state creates the CA key, certificate and signing policy. It also publishes the certificate to
the mine where it can be easily retrieved by other minions.
/srv/salt/ca.sls
.. code-block:: yaml
salt-minion:
service.running:
- enable: True
- listen:
- file: /etc/salt/minion.d/signing_policies.conf
/etc/salt/minion.d/signing_policies.conf:
file.managed:
- source: salt://signing_policies.conf
/etc/pki:
file.directory
/etc/pki/issued_certs:
file.directory
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
- managed_private_key:
name: /etc/pki/ca.key
bits: 4096
backup: True
- require:
- file: /etc/pki
mine.send:
module.run:
- func: x509.get_pem_entries
- kwargs:
glob_path: /etc/pki/ca.crt
- onchanges:
- x509: /etc/pki/ca.crt
The signing policy defines properties that override any property requested or included in a CRL. It also
can define a restricted list of minons which are allowed to remotely invoke this signing policy.
/srv/salt/signing_policies.conf
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical keyEncipherment"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
This state will instruct all minions to trust certificates signed by our new CA.
Using jinja to strip newlines from the text avoids dealing with newlines in the rendered yaml,
and the :mod:`sign_remote_certificate <salt.states.x509.sign_remote_certificate>` state will
handle properly formatting the text before writing the output.
/srv/salt/cert.sls
.. code-block:: jinja
/usr/local/share/ca-certificates:
file.directory
/usr/local/share/ca-certificates/intca.crt:
x509.pem_managed:
- text: {{ salt['mine.get']('ca', 'x509.get_pem_entries')['ca']['/etc/pki/ca.crt']|replace('\\n', '') }}
This state creates a private key then requests a certificate signed by ca according to the www policy.
/srv/salt/www.sls
.. code-block:: yaml
/etc/pki/www.crt:
x509.certificate_managed:
- ca_server: ca
- signing_policy: www
- public_key: /etc/pki/www.key
- CN: www.example.com
- days_remaining: 30
- backup: True
- managed_private_key:
name: /etc/pki/www.key
bits: 4096
backup: True
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import datetime
import os
import re
import copy
# Import Salt Libs
import salt.exceptions
import salt.utils.stringutils
# Import 3rd-party libs
from salt.ext import six
try:
from M2Crypto.RSA import RSAError
except ImportError:
RSAError = Exception('RSA Error')
def __virtual__():
'''
only load this module if the corresponding execution module is loaded
'''
if 'x509.get_pem_entry' in __salt__:
return 'x509'
else:
return False, 'Could not load x509 state: the x509 is not available'
def _revoked_to_list(revs):
'''
Turn the mess of OrderedDicts and Lists into a list of dicts for
use in the CRL module.
'''
list_ = []
for rev in revs:
for rev_name, props in six.iteritems(
rev): # pylint: disable=unused-variable
dict_ = {}
for prop in props:
for propname, val in six.iteritems(prop):
if isinstance(val, datetime.datetime):
val = val.strftime('%Y-%m-%d %H:%M:%S')
dict_[propname] = val
list_.append(dict_)
return list_
def _get_file_args(name, **kwargs):
valid_file_args = ['user',
'group',
'mode',
'makedirs',
'dir_mode',
'backup',
'create',
'follow_symlinks',
'check_cmd']
file_args = {}
extra_args = {}
for k, v in kwargs.items():
if k in valid_file_args:
file_args[k] = v
else:
extra_args[k] = v
file_args['name'] = name
return file_args, extra_args
def _check_private_key(name, bits=2048, passphrase=None,
new=False, overwrite=False):
current_bits = 0
if os.path.isfile(name):
try:
current_bits = __salt__['x509.get_private_key_size'](
private_key=name, passphrase=passphrase)
except salt.exceptions.SaltInvocationError:
pass
except RSAError:
if not overwrite:
raise salt.exceptions.CommandExecutionError(
'The provided passphrase cannot decrypt the private key.')
return current_bits == bits and not new
def private_key_managed(name,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
new=False,
overwrite=False,
verbose=True,
**kwargs):
'''
Manage a private key's existence.
name:
Path to the private key
bits:
Key length in bits. Default 2048.
passphrase:
Passphrase for encrypting the private key.
cipher:
Cipher for encrypting the private key.
new:
Always create a new key. Defaults to False.
Combining new with :mod:`prereq <salt.states.requsities.preqreq>`, or when used as part of a
`managed_private_key` can allow key rotation whenever a new certificiate is generated.
overwrite:
Overwrite an existing private key if the provided passphrase cannot decrypt it.
verbose:
Provide visual feedback on stdout, dots while key is generated.
Default is True.
.. versionadded:: 2016.11.0
kwargs:
Any kwargs supported by file.managed are supported.
Example:
The jinja templating in this example ensures a private key is generated if the file doesn't exist
and that a new private key is generated whenever the certificate that uses it is to be renewed.
.. code-block:: jinja
/etc/pki/www.key:
x509.private_key_managed:
- bits: 4096
- new: True
{% if salt['file.file_exists']('/etc/pki/www.key') -%}
- prereq:
- x509: /etc/pki/www.crt
{%- endif %}
'''
file_args, kwargs = _get_file_args(name, **kwargs)
new_key = False
if _check_private_key(
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
file_args['contents'] = __salt__['x509.get_pem_entry'](
name, pem_type='RSA PRIVATE KEY')
else:
new_key = True
file_args['contents'] = __salt__['x509.create_private_key'](
text=True, bits=bits, passphrase=passphrase, cipher=cipher, verbose=verbose)
# Ensure the key contents are a string before passing it along
file_args['contents'] = salt.utils.stringutils.to_str(file_args['contents'])
ret = __states__['file.managed'](**file_args)
if ret['changes'] and new_key:
ret['changes'] = {'new': 'New private key generated'}
return ret
def csr_managed(name,
**kwargs):
'''
Manage a Certificate Signing Request
name:
Path to the CSR
properties:
The properties to be added to the certificate request, including items like subject, extensions
and public key. See above for valid properties.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Example:
.. code-block:: yaml
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
- DomainController: 'ASN1:UTF8String:SomeOneSomeWhere'
- ext_mapping:
'1.3.6.1.4.1.311.20.2': 'DomainController'
'''
try:
old = __salt__['x509.read_csr'](name)
except salt.exceptions.SaltInvocationError:
old = '{0} is not a valid csr.'.format(name)
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = __salt__['x509.create_csr'](text=True, **kwargs)
ret = __states__['file.managed'](**file_args)
if ret['changes']:
new = __salt__['x509.read_csr'](file_args['contents'])
if old != new:
ret['changes'] = {"Old": old, "New": new}
return ret
def certificate_managed(name,
days_remaining=90,
managed_private_key=None,
append_certs=None,
**kwargs):
'''
Manage a Certificate
name
Path to the certificate
days_remaining : 90
The minimum number of days remaining when the certificate should be
recreated. A value of 0 disables automatic renewal.
managed_private_key
Manages the private key corresponding to the certificate. All of the
arguments supported by :py:func:`x509.private_key_managed
<salt.states.x509.private_key_managed>` are supported. If `name` is not
speicified or is the same as the name of the certificate, the private
key and certificate will be written together in the same file.
append_certs:
A list of certificates to be appended to the managed file.
kwargs:
Any arguments supported by :py:func:`x509.create_certificate
<salt.modules.x509.create_certificate>` or :py:func:`file.managed
<salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Examples:
.. code-block:: yaml
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
.. code-block:: yaml
/etc/ssl/www.crt:
x509.certificate_managed:
- ca_server: pki
- signing_policy: www
- public_key: /etc/ssl/www.key
- CN: www.example.com
- days_valid: 90
- days_remaining: 30
- backup: True
'''
if 'path' in kwargs:
name = kwargs.pop('path')
file_args, kwargs = _get_file_args(name, **kwargs)
rotate_private_key = False
new_private_key = False
if managed_private_key:
private_key_args = {
'name': name,
'new': False,
'overwrite': False,
'bits': 2048,
'passphrase': None,
'cipher': 'aes_128_cbc',
'verbose': True
}
private_key_args.update(managed_private_key)
kwargs['public_key_passphrase'] = private_key_args['passphrase']
if private_key_args['new']:
rotate_private_key = True
private_key_args['new'] = False
if _check_private_key(private_key_args['name'],
bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
new=private_key_args['new'],
overwrite=private_key_args['overwrite']):
private_key = __salt__['x509.get_pem_entry'](
private_key_args['name'], pem_type='RSA PRIVATE KEY')
else:
new_private_key = True
private_key = __salt__['x509.create_private_key'](text=True, bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
cipher=private_key_args['cipher'],
verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_certificate'](certificate=name)
current_comp = copy.deepcopy(current)
if 'serial_number' not in kwargs:
current_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
current_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
current_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
current_comp.pop('Not Before')
current_comp.pop('MD5 Finger Print')
current_comp.pop('SHA1 Finger Print')
current_comp.pop('SHA-256 Finger Print')
current_notafter = current_comp.pop('Not After')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid Certificate.'.format(name)
else:
current = '{0} does not exist.'.format(name)
if 'ca_server' in kwargs and 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified if ca_server is.')
new = __salt__['x509.create_certificate'](testrun=False, text=True, **kwargs)
new = __salt__['x509.read_certificate'](certificate=new)
newcert = __salt__['x509.create_certificate'](testrun=True, **kwargs)
if isinstance(new, dict):
new_comp = copy.deepcopy(new)
if 'serial_number' not in kwargs:
new_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
new_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
new_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
new_comp.pop('Not Before')
new_comp.pop('Not After')
new_comp.pop('MD5 Finger Print')
new_comp.pop('SHA1 Finger Print')
new_comp.pop('SHA-256 Finger Print')
new_issuer_public_key = new_issuer_public_key = newcert.pop('Issuer Public Key')
else:
new_comp = new
new_certificate = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_signature'](name, new_issuer_public_key)):
certificate = __salt__['x509.get_pem_entry'](
name, pem_type='CERTIFICATE')
else:
if rotate_private_key and not new_private_key:
new_private_key = True
private_key = __salt__['x509.create_private_key'](
text=True, bits=private_key_args['bits'], verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
new_certificate = True
certificate = __salt__['x509.create_certificate'](text=True, **kwargs)
file_args['contents'] = ''
private_ret = {}
if managed_private_key:
if private_key_args['name'] == name:
file_args['contents'] = private_key
else:
private_file_args = copy.deepcopy(file_args)
unique_private_file_args, _ = _get_file_args(**private_key_args)
private_file_args.update(unique_private_file_args)
private_file_args['contents'] = private_key
private_ret = __states__['file.managed'](**private_file_args)
if not private_ret['result']:
return private_ret
file_args['contents'] += salt.utils.stringutils.to_str(certificate)
if not append_certs:
append_certs = []
for append_cert in append_certs:
file_args[
'contents'] += __salt__['x509.get_pem_entry'](append_cert, pem_type='CERTIFICATE')
file_args['show_changes'] = False
ret = __states__['file.managed'](**file_args)
if ret['changes']:
ret['changes'] = {'Certificate': ret['changes']}
else:
ret['changes'] = {}
if private_ret and private_ret['changes']:
ret['changes']['Private Key'] = private_ret['changes']
if new_private_key:
ret['changes']['Private Key'] = 'New private key generated'
if new_certificate:
ret['changes']['Certificate'] = {
'Old': current,
'New': __salt__['x509.read_certificate'](certificate=certificate)}
return ret
def pem_managed(name,
text,
backup=False,
**kwargs):
'''
Manage the contents of a PEM file directly with the content in text, ensuring correct formatting.
name:
The path to the file to manage
text:
The PEM formatted text to write.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
'''
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = salt.utils.stringutils.to_str(__salt__['x509.get_pem_entry'](text=text))
return __states__['file.managed'](**file_args)
|
saltstack/salt
|
salt/states/x509.py
|
pem_managed
|
python
|
def pem_managed(name,
text,
backup=False,
**kwargs):
'''
Manage the contents of a PEM file directly with the content in text, ensuring correct formatting.
name:
The path to the file to manage
text:
The PEM formatted text to write.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
'''
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = salt.utils.stringutils.to_str(__salt__['x509.get_pem_entry'](text=text))
return __states__['file.managed'](**file_args)
|
Manage the contents of a PEM file directly with the content in text, ensuring correct formatting.
name:
The path to the file to manage
text:
The PEM formatted text to write.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/x509.py#L734-L753
|
[
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def _get_file_args(name, **kwargs):\n valid_file_args = ['user',\n 'group',\n 'mode',\n 'makedirs',\n 'dir_mode',\n 'backup',\n 'create',\n 'follow_symlinks',\n 'check_cmd']\n file_args = {}\n extra_args = {}\n for k, v in kwargs.items():\n if k in valid_file_args:\n file_args[k] = v\n else:\n extra_args[k] = v\n file_args['name'] = name\n return file_args, extra_args\n"
] |
# -*- coding: utf-8 -*-
'''
Manage X509 Certificates
.. versionadded:: 2015.8.0
:depends: M2Crypto
This module can enable managing a complete PKI infrastructure including creating private keys, CA's,
certificates and CRLs. It includes the ability to generate a private key on a server, and have the
corresponding public key sent to a remote CA to create a CA signed certificate. This can be done in
a secure manner, where private keys are always generated locally and never moved across the network.
Here is a simple example scenario. In this example ``ca`` is the ca server,
and ``www`` is a web server that needs a certificate signed by ``ca``.
For remote signing, peers must be permitted to remotely call the
:mod:`sign_remote_certificate <salt.modules.x509.sign_remote_certificate>` function.
/etc/salt/master.d/peer.conf
.. code-block:: yaml
peer:
.*:
- x509.sign_remote_certificate
/srv/salt/top.sls
.. code-block:: yaml
base:
'*':
- cert
'ca':
- ca
'www':
- www
This state creates the CA key, certificate and signing policy. It also publishes the certificate to
the mine where it can be easily retrieved by other minions.
/srv/salt/ca.sls
.. code-block:: yaml
salt-minion:
service.running:
- enable: True
- listen:
- file: /etc/salt/minion.d/signing_policies.conf
/etc/salt/minion.d/signing_policies.conf:
file.managed:
- source: salt://signing_policies.conf
/etc/pki:
file.directory
/etc/pki/issued_certs:
file.directory
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
- managed_private_key:
name: /etc/pki/ca.key
bits: 4096
backup: True
- require:
- file: /etc/pki
mine.send:
module.run:
- func: x509.get_pem_entries
- kwargs:
glob_path: /etc/pki/ca.crt
- onchanges:
- x509: /etc/pki/ca.crt
The signing policy defines properties that override any property requested or included in a CRL. It also
can define a restricted list of minons which are allowed to remotely invoke this signing policy.
/srv/salt/signing_policies.conf
.. code-block:: yaml
x509_signing_policies:
www:
- minions: 'www'
- signing_private_key: /etc/pki/ca.key
- signing_cert: /etc/pki/ca.crt
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:false"
- keyUsage: "critical keyEncipherment"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 90
- copypath: /etc/pki/issued_certs/
This state will instruct all minions to trust certificates signed by our new CA.
Using jinja to strip newlines from the text avoids dealing with newlines in the rendered yaml,
and the :mod:`sign_remote_certificate <salt.states.x509.sign_remote_certificate>` state will
handle properly formatting the text before writing the output.
/srv/salt/cert.sls
.. code-block:: jinja
/usr/local/share/ca-certificates:
file.directory
/usr/local/share/ca-certificates/intca.crt:
x509.pem_managed:
- text: {{ salt['mine.get']('ca', 'x509.get_pem_entries')['ca']['/etc/pki/ca.crt']|replace('\\n', '') }}
This state creates a private key then requests a certificate signed by ca according to the www policy.
/srv/salt/www.sls
.. code-block:: yaml
/etc/pki/www.crt:
x509.certificate_managed:
- ca_server: ca
- signing_policy: www
- public_key: /etc/pki/www.key
- CN: www.example.com
- days_remaining: 30
- backup: True
- managed_private_key:
name: /etc/pki/www.key
bits: 4096
backup: True
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import datetime
import os
import re
import copy
# Import Salt Libs
import salt.exceptions
import salt.utils.stringutils
# Import 3rd-party libs
from salt.ext import six
try:
from M2Crypto.RSA import RSAError
except ImportError:
RSAError = Exception('RSA Error')
def __virtual__():
'''
only load this module if the corresponding execution module is loaded
'''
if 'x509.get_pem_entry' in __salt__:
return 'x509'
else:
return False, 'Could not load x509 state: the x509 is not available'
def _revoked_to_list(revs):
'''
Turn the mess of OrderedDicts and Lists into a list of dicts for
use in the CRL module.
'''
list_ = []
for rev in revs:
for rev_name, props in six.iteritems(
rev): # pylint: disable=unused-variable
dict_ = {}
for prop in props:
for propname, val in six.iteritems(prop):
if isinstance(val, datetime.datetime):
val = val.strftime('%Y-%m-%d %H:%M:%S')
dict_[propname] = val
list_.append(dict_)
return list_
def _get_file_args(name, **kwargs):
valid_file_args = ['user',
'group',
'mode',
'makedirs',
'dir_mode',
'backup',
'create',
'follow_symlinks',
'check_cmd']
file_args = {}
extra_args = {}
for k, v in kwargs.items():
if k in valid_file_args:
file_args[k] = v
else:
extra_args[k] = v
file_args['name'] = name
return file_args, extra_args
def _check_private_key(name, bits=2048, passphrase=None,
new=False, overwrite=False):
current_bits = 0
if os.path.isfile(name):
try:
current_bits = __salt__['x509.get_private_key_size'](
private_key=name, passphrase=passphrase)
except salt.exceptions.SaltInvocationError:
pass
except RSAError:
if not overwrite:
raise salt.exceptions.CommandExecutionError(
'The provided passphrase cannot decrypt the private key.')
return current_bits == bits and not new
def private_key_managed(name,
bits=2048,
passphrase=None,
cipher='aes_128_cbc',
new=False,
overwrite=False,
verbose=True,
**kwargs):
'''
Manage a private key's existence.
name:
Path to the private key
bits:
Key length in bits. Default 2048.
passphrase:
Passphrase for encrypting the private key.
cipher:
Cipher for encrypting the private key.
new:
Always create a new key. Defaults to False.
Combining new with :mod:`prereq <salt.states.requsities.preqreq>`, or when used as part of a
`managed_private_key` can allow key rotation whenever a new certificiate is generated.
overwrite:
Overwrite an existing private key if the provided passphrase cannot decrypt it.
verbose:
Provide visual feedback on stdout, dots while key is generated.
Default is True.
.. versionadded:: 2016.11.0
kwargs:
Any kwargs supported by file.managed are supported.
Example:
The jinja templating in this example ensures a private key is generated if the file doesn't exist
and that a new private key is generated whenever the certificate that uses it is to be renewed.
.. code-block:: jinja
/etc/pki/www.key:
x509.private_key_managed:
- bits: 4096
- new: True
{% if salt['file.file_exists']('/etc/pki/www.key') -%}
- prereq:
- x509: /etc/pki/www.crt
{%- endif %}
'''
file_args, kwargs = _get_file_args(name, **kwargs)
new_key = False
if _check_private_key(
name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite):
file_args['contents'] = __salt__['x509.get_pem_entry'](
name, pem_type='RSA PRIVATE KEY')
else:
new_key = True
file_args['contents'] = __salt__['x509.create_private_key'](
text=True, bits=bits, passphrase=passphrase, cipher=cipher, verbose=verbose)
# Ensure the key contents are a string before passing it along
file_args['contents'] = salt.utils.stringutils.to_str(file_args['contents'])
ret = __states__['file.managed'](**file_args)
if ret['changes'] and new_key:
ret['changes'] = {'new': 'New private key generated'}
return ret
def csr_managed(name,
**kwargs):
'''
Manage a Certificate Signing Request
name:
Path to the CSR
properties:
The properties to be added to the certificate request, including items like subject, extensions
and public key. See above for valid properties.
kwargs:
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Example:
.. code-block:: yaml
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
/etc/pki/mycert.csr:
x509.csr_managed:
- private_key: /etc/pki/mycert.key
- CN: www.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- keyUsage: 'critical dataEncipherment'
- DomainController: 'ASN1:UTF8String:SomeOneSomeWhere'
- ext_mapping:
'1.3.6.1.4.1.311.20.2': 'DomainController'
'''
try:
old = __salt__['x509.read_csr'](name)
except salt.exceptions.SaltInvocationError:
old = '{0} is not a valid csr.'.format(name)
file_args, kwargs = _get_file_args(name, **kwargs)
file_args['contents'] = __salt__['x509.create_csr'](text=True, **kwargs)
ret = __states__['file.managed'](**file_args)
if ret['changes']:
new = __salt__['x509.read_csr'](file_args['contents'])
if old != new:
ret['changes'] = {"Old": old, "New": new}
return ret
def certificate_managed(name,
days_remaining=90,
managed_private_key=None,
append_certs=None,
**kwargs):
'''
Manage a Certificate
name
Path to the certificate
days_remaining : 90
The minimum number of days remaining when the certificate should be
recreated. A value of 0 disables automatic renewal.
managed_private_key
Manages the private key corresponding to the certificate. All of the
arguments supported by :py:func:`x509.private_key_managed
<salt.states.x509.private_key_managed>` are supported. If `name` is not
speicified or is the same as the name of the certificate, the private
key and certificate will be written together in the same file.
append_certs:
A list of certificates to be appended to the managed file.
kwargs:
Any arguments supported by :py:func:`x509.create_certificate
<salt.modules.x509.create_certificate>` or :py:func:`file.managed
<salt.states.file.managed>` are supported.
ext_mapping:
Provide additional X509v3 extension mappings. This argument should be
in the form of a dictionary and should include both the OID and the
friendly name for the extension.
.. versionadded:: Neon
Examples:
.. code-block:: yaml
/etc/pki/ca.crt:
x509.certificate_managed:
- signing_private_key: /etc/pki/ca.key
- CN: ca.example.com
- C: US
- ST: Utah
- L: Salt Lake City
- basicConstraints: "critical CA:true"
- keyUsage: "critical cRLSign, keyCertSign"
- subjectKeyIdentifier: hash
- authorityKeyIdentifier: keyid,issuer:always
- days_valid: 3650
- days_remaining: 0
- backup: True
.. code-block:: yaml
/etc/ssl/www.crt:
x509.certificate_managed:
- ca_server: pki
- signing_policy: www
- public_key: /etc/ssl/www.key
- CN: www.example.com
- days_valid: 90
- days_remaining: 30
- backup: True
'''
if 'path' in kwargs:
name = kwargs.pop('path')
file_args, kwargs = _get_file_args(name, **kwargs)
rotate_private_key = False
new_private_key = False
if managed_private_key:
private_key_args = {
'name': name,
'new': False,
'overwrite': False,
'bits': 2048,
'passphrase': None,
'cipher': 'aes_128_cbc',
'verbose': True
}
private_key_args.update(managed_private_key)
kwargs['public_key_passphrase'] = private_key_args['passphrase']
if private_key_args['new']:
rotate_private_key = True
private_key_args['new'] = False
if _check_private_key(private_key_args['name'],
bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
new=private_key_args['new'],
overwrite=private_key_args['overwrite']):
private_key = __salt__['x509.get_pem_entry'](
private_key_args['name'], pem_type='RSA PRIVATE KEY')
else:
new_private_key = True
private_key = __salt__['x509.create_private_key'](text=True, bits=private_key_args['bits'],
passphrase=private_key_args['passphrase'],
cipher=private_key_args['cipher'],
verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_certificate'](certificate=name)
current_comp = copy.deepcopy(current)
if 'serial_number' not in kwargs:
current_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
current_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
current_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
current_comp.pop('Not Before')
current_comp.pop('MD5 Finger Print')
current_comp.pop('SHA1 Finger Print')
current_comp.pop('SHA-256 Finger Print')
current_notafter = current_comp.pop('Not After')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid Certificate.'.format(name)
else:
current = '{0} does not exist.'.format(name)
if 'ca_server' in kwargs and 'signing_policy' not in kwargs:
raise salt.exceptions.SaltInvocationError(
'signing_policy must be specified if ca_server is.')
new = __salt__['x509.create_certificate'](testrun=False, text=True, **kwargs)
new = __salt__['x509.read_certificate'](certificate=new)
newcert = __salt__['x509.create_certificate'](testrun=True, **kwargs)
if isinstance(new, dict):
new_comp = copy.deepcopy(new)
if 'serial_number' not in kwargs:
new_comp.pop('Serial Number')
if 'signing_cert' not in kwargs:
try:
new_comp['X509v3 Extensions']['authorityKeyIdentifier'] = (
re.sub(r'serial:([0-9A-F]{2}:)*[0-9A-F]{2}', 'serial:--',
new_comp['X509v3 Extensions']['authorityKeyIdentifier']))
except KeyError:
pass
new_comp.pop('Not Before')
new_comp.pop('Not After')
new_comp.pop('MD5 Finger Print')
new_comp.pop('SHA1 Finger Print')
new_comp.pop('SHA-256 Finger Print')
new_issuer_public_key = new_issuer_public_key = newcert.pop('Issuer Public Key')
else:
new_comp = new
new_certificate = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_signature'](name, new_issuer_public_key)):
certificate = __salt__['x509.get_pem_entry'](
name, pem_type='CERTIFICATE')
else:
if rotate_private_key and not new_private_key:
new_private_key = True
private_key = __salt__['x509.create_private_key'](
text=True, bits=private_key_args['bits'], verbose=private_key_args['verbose'])
kwargs['public_key'] = private_key
new_certificate = True
certificate = __salt__['x509.create_certificate'](text=True, **kwargs)
file_args['contents'] = ''
private_ret = {}
if managed_private_key:
if private_key_args['name'] == name:
file_args['contents'] = private_key
else:
private_file_args = copy.deepcopy(file_args)
unique_private_file_args, _ = _get_file_args(**private_key_args)
private_file_args.update(unique_private_file_args)
private_file_args['contents'] = private_key
private_ret = __states__['file.managed'](**private_file_args)
if not private_ret['result']:
return private_ret
file_args['contents'] += salt.utils.stringutils.to_str(certificate)
if not append_certs:
append_certs = []
for append_cert in append_certs:
file_args[
'contents'] += __salt__['x509.get_pem_entry'](append_cert, pem_type='CERTIFICATE')
file_args['show_changes'] = False
ret = __states__['file.managed'](**file_args)
if ret['changes']:
ret['changes'] = {'Certificate': ret['changes']}
else:
ret['changes'] = {}
if private_ret and private_ret['changes']:
ret['changes']['Private Key'] = private_ret['changes']
if new_private_key:
ret['changes']['Private Key'] = 'New private key generated'
if new_certificate:
ret['changes']['Certificate'] = {
'Old': current,
'New': __salt__['x509.read_certificate'](certificate=certificate)}
return ret
def crl_managed(name,
signing_private_key,
signing_private_key_passphrase=None,
signing_cert=None,
revoked=None,
days_valid=100,
digest="",
days_remaining=30,
include_expired=False,
**kwargs):
'''
Manage a Certificate Revocation List
name
Path to the certificate
signing_private_key
The private key that will be used to sign this crl. This is
usually your CA's private key.
signing_private_key_passphrase
Passphrase to decrypt the private key.
signing_cert
The certificate of the authority that will be used to sign this crl.
This is usually your CA's certificate.
revoked
A list of certificates to revoke. Must include either a serial number or a
the certificate itself. Can optionally include the revocation date and
notAfter date from the certificate. See example below for details.
days_valid : 100
The number of days the certificate should be valid for.
digest
The digest to use for signing the CRL. This has no effect on versions
of pyOpenSSL less than 0.14.
days_remaining : 30
The crl should be automatically recreated if there are less than
``days_remaining`` days until the crl expires. Set to 0 to disable
automatic renewal.
include_expired : False
If ``True``, include expired certificates in the CRL.
kwargs
Any arguments supported by :py:func:`file.managed <salt.states.file.managed>` are supported.
Example:
.. code-block:: yaml
/etc/pki/ca.crl:
x509.crl_managed:
- signing_private_key: /etc/pki/myca.key
- signing_cert: /etc/pki/myca.crt
- revoked:
- compromized_Web_key:
- certificate: /etc/pki/certs/badweb.crt
- revocation_date: 2015-03-01 00:00:00
- reason: keyCompromise
- terminated_vpn_user:
- serial_number: D6:D2:DC:D8:4D:5C:C0:F4
- not_after: 2016-01-01 00:00:00
- revocation_date: 2015-02-25 00:00:00
- reason: cessationOfOperation
'''
if revoked is None:
revoked = []
revoked = _revoked_to_list(revoked)
current_days_remaining = 0
current_comp = {}
if os.path.isfile(name):
try:
current = __salt__['x509.read_crl'](crl=name)
current_comp = current.copy()
current_comp.pop('Last Update')
current_notafter = current_comp.pop('Next Update')
current_days_remaining = (
datetime.datetime.strptime(current_notafter, '%Y-%m-%d %H:%M:%S') -
datetime.datetime.now()).days
if days_remaining == 0:
days_remaining = current_days_remaining - 1
except salt.exceptions.SaltInvocationError:
current = '{0} is not a valid CRL.'.format(name)
else:
current = '{0} does not exist.'.format(name)
new_crl = __salt__['x509.create_crl'](text=True, signing_private_key=signing_private_key,
signing_private_key_passphrase=signing_private_key_passphrase,
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid,
digest=digest, include_expired=include_expired)
new = __salt__['x509.read_crl'](crl=new_crl)
new_comp = new.copy()
new_comp.pop('Last Update')
new_comp.pop('Next Update')
file_args, kwargs = _get_file_args(name, **kwargs)
new_crl_created = False
if (current_comp == new_comp and
current_days_remaining > days_remaining and
__salt__['x509.verify_crl'](name, signing_cert)):
file_args['contents'] = __salt__[
'x509.get_pem_entry'](name, pem_type='X509 CRL')
else:
new_crl_created = True
file_args['contents'] = new_crl
ret = __states__['file.managed'](**file_args)
if new_crl_created:
ret['changes'] = {'Old': current, 'New': __salt__[
'x509.read_crl'](crl=new_crl)}
return ret
|
saltstack/salt
|
salt/utils/dateutils.py
|
date_cast
|
python
|
def date_cast(date):
'''
Casts any object into a datetime.datetime object
date
any datetime, time string representation...
'''
if date is None:
return datetime.datetime.now()
elif isinstance(date, datetime.datetime):
return date
# fuzzy date
try:
if isinstance(date, six.string_types):
try:
if HAS_TIMELIB:
# py3: yes, timelib.strtodatetime wants bytes, not str :/
return timelib.strtodatetime(
salt.utils.stringutils.to_bytes(date))
except ValueError:
pass
# not parsed yet, obviously a timestamp?
if date.isdigit():
date = int(date)
else:
date = float(date)
return datetime.datetime.fromtimestamp(date)
except Exception:
if HAS_TIMELIB:
raise ValueError('Unable to parse {0}'.format(date))
raise RuntimeError(
'Unable to parse {0}. Consider installing timelib'.format(date))
|
Casts any object into a datetime.datetime object
date
any datetime, time string representation...
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dateutils.py#L25-L60
| null |
# -*- coding: utf-8 -*-
'''
Convenience functions for dealing with datetime classes
'''
from __future__ import absolute_import, division, print_function, unicode_literals
# Import Python libs
import datetime
# Import Salt libs
import salt.utils.stringutils
from salt.utils.decorators.jinja import jinja_filter
# Import 3rd-party libs
from salt.ext import six
try:
import timelib
HAS_TIMELIB = True
except ImportError:
HAS_TIMELIB = False
@jinja_filter('date_format')
@jinja_filter('strftime')
def strftime(date=None, format="%Y-%m-%d"):
'''
Converts date into a time-based string
date
any datetime, time string representation...
format
:ref:`strftime<http://docs.python.org/2/library/datetime.html#datetime.datetime.strftime>` format
>>> import datetime
>>> src = datetime.datetime(2002, 12, 25, 12, 00, 00, 00)
>>> strftime(src)
'2002-12-25'
>>> src = '2002/12/25'
>>> strftime(src)
'2002-12-25'
>>> src = 1040814000
>>> strftime(src)
'2002-12-25'
>>> src = '1040814000'
>>> strftime(src)
'2002-12-25'
'''
return date_cast(date).strftime(format)
def total_seconds(td):
'''
Takes a timedelta and returns the total number of seconds
represented by the object. Wrapper for the total_seconds()
method which does not exist in versions of Python < 2.7.
'''
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
|
saltstack/salt
|
salt/states/mssql_user.py
|
present
|
python
|
def present(name, login=None, domain=None, database=None, roles=None, options=None, **kwargs):
'''
Checks existance of the named user.
If not present, creates the user with the specified roles and options.
name
The name of the user to manage
login
If not specified, will be created WITHOUT LOGIN
domain
Creates a Windows authentication user.
Needs to be NetBIOS domain or hostname
database
The database of the user (not the login)
roles
Add this user to all the roles in the list
options
Can be a list of strings, a dictionary, or a list of dictionaries
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if domain and not login:
ret['result'] = False
ret['comment'] = 'domain cannot be set without login'
return ret
if __salt__['mssql.user_exists'](name, domain=domain, database=database, **kwargs):
ret['comment'] = 'User {0} is already present (Not going to try to set its roles or options)'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} is set to be added'.format(name)
return ret
user_created = __salt__['mssql.user_create'](name, login=login,
domain=domain,
database=database,
roles=roles,
options=_normalize_options(options),
**kwargs)
if user_created is not True: # Non-empty strings are also evaluated to True, so we cannot use if not user_created:
ret['result'] = False
ret['comment'] += 'User {0} failed to be added: {1}'.format(name, user_created)
return ret
ret['comment'] += 'User {0} has been added'.format(name)
ret['changes'][name] = 'Present'
return ret
|
Checks existance of the named user.
If not present, creates the user with the specified roles and options.
name
The name of the user to manage
login
If not specified, will be created WITHOUT LOGIN
domain
Creates a Windows authentication user.
Needs to be NetBIOS domain or hostname
database
The database of the user (not the login)
roles
Add this user to all the roles in the list
options
Can be a list of strings, a dictionary, or a list of dictionaries
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mssql_user.py#L37-L85
|
[
"def _normalize_options(options):\n if type(options) in [dict, collections.OrderedDict]:\n return ['{0}={1}'.format(k, v) for k, v in options.items()]\n if type(options) is list and (not options or type(options[0]) is str):\n return options\n # Invalid options\n if type(options) is not list or type(options[0]) not in [dict, collections.OrderedDict]:\n return []\n return [o for d in options for o in _normalize_options(d)]\n"
] |
# -*- coding: utf-8 -*-
'''
Management of Microsoft SQLServer Users
=======================================
The mssql_user module is used to create
and manage SQL Server Users
.. code-block:: yaml
frank:
mssql_user.present:
- database: yolo
'''
from __future__ import absolute_import, print_function, unicode_literals
import collections
def __virtual__():
'''
Only load if the mssql module is present
'''
return 'mssql.version' in __salt__
def _normalize_options(options):
if type(options) in [dict, collections.OrderedDict]:
return ['{0}={1}'.format(k, v) for k, v in options.items()]
if type(options) is list and (not options or type(options[0]) is str):
return options
# Invalid options
if type(options) is not list or type(options[0]) not in [dict, collections.OrderedDict]:
return []
return [o for d in options for o in _normalize_options(d)]
def absent(name, **kwargs):
'''
Ensure that the named user is absent
name
The username of the user to remove
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if not __salt__['mssql.user_exists'](name):
ret['comment'] = 'User {0} is not present'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} is set to be removed'.format(name)
return ret
if __salt__['mssql.user_remove'](name, **kwargs):
ret['comment'] = 'User {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
# else:
ret['result'] = False
ret['comment'] = 'User {0} failed to be removed'.format(name)
return ret
|
saltstack/salt
|
salt/states/mssql_user.py
|
absent
|
python
|
def absent(name, **kwargs):
'''
Ensure that the named user is absent
name
The username of the user to remove
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if not __salt__['mssql.user_exists'](name):
ret['comment'] = 'User {0} is not present'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} is set to be removed'.format(name)
return ret
if __salt__['mssql.user_remove'](name, **kwargs):
ret['comment'] = 'User {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
# else:
ret['result'] = False
ret['comment'] = 'User {0} failed to be removed'.format(name)
return ret
|
Ensure that the named user is absent
name
The username of the user to remove
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mssql_user.py#L88-L114
| null |
# -*- coding: utf-8 -*-
'''
Management of Microsoft SQLServer Users
=======================================
The mssql_user module is used to create
and manage SQL Server Users
.. code-block:: yaml
frank:
mssql_user.present:
- database: yolo
'''
from __future__ import absolute_import, print_function, unicode_literals
import collections
def __virtual__():
'''
Only load if the mssql module is present
'''
return 'mssql.version' in __salt__
def _normalize_options(options):
if type(options) in [dict, collections.OrderedDict]:
return ['{0}={1}'.format(k, v) for k, v in options.items()]
if type(options) is list and (not options or type(options[0]) is str):
return options
# Invalid options
if type(options) is not list or type(options[0]) not in [dict, collections.OrderedDict]:
return []
return [o for d in options for o in _normalize_options(d)]
def present(name, login=None, domain=None, database=None, roles=None, options=None, **kwargs):
'''
Checks existance of the named user.
If not present, creates the user with the specified roles and options.
name
The name of the user to manage
login
If not specified, will be created WITHOUT LOGIN
domain
Creates a Windows authentication user.
Needs to be NetBIOS domain or hostname
database
The database of the user (not the login)
roles
Add this user to all the roles in the list
options
Can be a list of strings, a dictionary, or a list of dictionaries
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if domain and not login:
ret['result'] = False
ret['comment'] = 'domain cannot be set without login'
return ret
if __salt__['mssql.user_exists'](name, domain=domain, database=database, **kwargs):
ret['comment'] = 'User {0} is already present (Not going to try to set its roles or options)'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} is set to be added'.format(name)
return ret
user_created = __salt__['mssql.user_create'](name, login=login,
domain=domain,
database=database,
roles=roles,
options=_normalize_options(options),
**kwargs)
if user_created is not True: # Non-empty strings are also evaluated to True, so we cannot use if not user_created:
ret['result'] = False
ret['comment'] += 'User {0} failed to be added: {1}'.format(name, user_created)
return ret
ret['comment'] += 'User {0} has been added'.format(name)
ret['changes'][name] = 'Present'
return ret
|
saltstack/salt
|
salt/modules/jinja.py
|
_strip_odict
|
python
|
def _strip_odict(wrapped):
'''
dump to json and load it again, replaces OrderedDicts with regular ones
'''
@functools.wraps(wrapped)
def strip(*args):
return salt.utils.json.loads(salt.utils.json.dumps(wrapped(*args)))
return strip
|
dump to json and load it again, replaces OrderedDicts with regular ones
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jinja.py#L23-L30
| null |
# -*- coding: utf-8 -*-
'''
Module for checking jinja maps and verifying the result of loading JSON/YAML
files
.. versionadded:: Neon
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import functools
import logging
import textwrap
# Import Salt libs
import salt.loader
import salt.template
import salt.utils.json
log = logging.getLogger(__name__)
@_strip_odict
def load_map(path, value):
'''
Loads the map at the specified path, and returns the specified value from
that map.
CLI Example:
.. code-block:: bash
# Assuming the map is loaded in your formula SLS as follows:
#
# {% from "myformula/map.jinja" import myformula with context %}
#
# the following syntax can be used to load the map and check the
# results:
salt myminion jinja.load_map myformula/map.jinja myformula
'''
tmplstr = textwrap.dedent('''\
{{% from "{path}" import {value} with context %}}
{{{{ {value} | tojson }}}}
'''.format(path=path, value=value))
return salt.template.compile_template_str(
tmplstr,
salt.loader.render(__opts__, __salt__),
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'])
@_strip_odict
def import_yaml(path):
'''
Loads YAML data from the specified path
CLI Example:
.. code-block:: bash
salt myminion jinja.import_yaml myformula/foo.yaml
'''
tmplstr = textwrap.dedent('''\
{{% import_yaml "{path}" as imported %}}
{{{{ imported | tojson }}}}
'''.format(path=path))
return salt.template.compile_template_str(
tmplstr,
salt.loader.render(__opts__, __salt__),
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'])
@_strip_odict
def import_json(path):
'''
Loads JSON data from the specified path
CLI Example:
.. code-block:: bash
salt myminion jinja.import_JSON myformula/foo.json
'''
tmplstr = textwrap.dedent('''\
{{% import_json "{path}" as imported %}}
{{{{ imported | tojson }}}}
'''.format(path=path))
return salt.template.compile_template_str(
tmplstr,
salt.loader.render(__opts__, __salt__),
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'])
|
saltstack/salt
|
salt/modules/jinja.py
|
load_map
|
python
|
def load_map(path, value):
'''
Loads the map at the specified path, and returns the specified value from
that map.
CLI Example:
.. code-block:: bash
# Assuming the map is loaded in your formula SLS as follows:
#
# {% from "myformula/map.jinja" import myformula with context %}
#
# the following syntax can be used to load the map and check the
# results:
salt myminion jinja.load_map myformula/map.jinja myformula
'''
tmplstr = textwrap.dedent('''\
{{% from "{path}" import {value} with context %}}
{{{{ {value} | tojson }}}}
'''.format(path=path, value=value))
return salt.template.compile_template_str(
tmplstr,
salt.loader.render(__opts__, __salt__),
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'])
|
Loads the map at the specified path, and returns the specified value from
that map.
CLI Example:
.. code-block:: bash
# Assuming the map is loaded in your formula SLS as follows:
#
# {% from "myformula/map.jinja" import myformula with context %}
#
# the following syntax can be used to load the map and check the
# results:
salt myminion jinja.load_map myformula/map.jinja myformula
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jinja.py#L34-L60
|
[
"def compile_template_str(template, renderers, default, blacklist, whitelist):\n '''\n Take template as a string and return the high data structure\n derived from the template.\n '''\n fn_ = salt.utils.files.mkstemp()\n with salt.utils.files.fopen(fn_, 'wb') as ofile:\n ofile.write(SLS_ENCODER(template)[0])\n return compile_template(fn_, renderers, default, blacklist, whitelist)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for checking jinja maps and verifying the result of loading JSON/YAML
files
.. versionadded:: Neon
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import functools
import logging
import textwrap
# Import Salt libs
import salt.loader
import salt.template
import salt.utils.json
log = logging.getLogger(__name__)
def _strip_odict(wrapped):
'''
dump to json and load it again, replaces OrderedDicts with regular ones
'''
@functools.wraps(wrapped)
def strip(*args):
return salt.utils.json.loads(salt.utils.json.dumps(wrapped(*args)))
return strip
@_strip_odict
@_strip_odict
def import_yaml(path):
'''
Loads YAML data from the specified path
CLI Example:
.. code-block:: bash
salt myminion jinja.import_yaml myformula/foo.yaml
'''
tmplstr = textwrap.dedent('''\
{{% import_yaml "{path}" as imported %}}
{{{{ imported | tojson }}}}
'''.format(path=path))
return salt.template.compile_template_str(
tmplstr,
salt.loader.render(__opts__, __salt__),
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'])
@_strip_odict
def import_json(path):
'''
Loads JSON data from the specified path
CLI Example:
.. code-block:: bash
salt myminion jinja.import_JSON myformula/foo.json
'''
tmplstr = textwrap.dedent('''\
{{% import_json "{path}" as imported %}}
{{{{ imported | tojson }}}}
'''.format(path=path))
return salt.template.compile_template_str(
tmplstr,
salt.loader.render(__opts__, __salt__),
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'])
|
saltstack/salt
|
salt/modules/pillar.py
|
get
|
python
|
def get(key,
default=KeyError,
merge=False,
merge_nested_lists=None,
delimiter=DEFAULT_TARGET_DELIM,
pillarenv=None,
saltenv=None):
'''
.. versionadded:: 0.14
Attempt to retrieve the named value from :ref:`in-memory pillar data
<pillar-in-memory>`. If the pillar key is not present in the in-memory
pillar, then the value specified in the ``default`` option (described
below) will be returned.
If the merge parameter is set to ``True``, the default will be recursively
merged into the returned pillar data.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict. This means that if a dict in pillar looks like this::
{'pkg': {'apache': 'httpd'}}
To retrieve the value associated with the ``apache`` key in the ``pkg``
dict this key can be passed as::
pkg:apache
key
The pillar key to get value from
default
The value specified by this option will be returned if the desired
pillar key does not exist.
If a default value is specified, then it will be an empty string,
unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in
which case an error will be raised.
merge : ``False``
If ``True``, the retrieved values will be merged into the passed
default. When the default and the retrieved value are both
dictionaries, the dictionaries will be recursively merged.
.. versionadded:: 2014.7.0
.. versionchanged:: 2016.3.7,2016.11.4,2017.7.0
If the default and the retrieved value are not of the same type,
then merging will be skipped and the retrieved value will be
returned. Earlier releases raised an error in these cases.
merge_nested_lists
If set to ``False``, lists nested within the retrieved pillar
dictionary will *overwrite* lists in ``default``. If set to ``True``,
nested lists will be *merged* into lists in ``default``. If unspecified
(the default), this option is inherited from the
:conf_minion:`pillar_merge_lists` minion config option.
.. note::
This option is ignored when ``merge`` is set to ``False``.
.. versionadded:: 2016.11.6
delimiter
Specify an alternate delimiter to use when traversing a nested dict.
This is useful for when the desired key contains a colon. See CLI
example below for usage.
.. versionadded:: 2014.7.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.0
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' pillar.get pkg:apache
salt '*' pillar.get abc::def|ghi delimiter='|'
'''
if not __opts__.get('pillar_raise_on_missing'):
if default is KeyError:
default = ''
opt_merge_lists = __opts__.get('pillar_merge_lists', False) if \
merge_nested_lists is None else merge_nested_lists
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
if merge:
if isinstance(default, dict):
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
{},
delimiter)
if isinstance(ret, collections.Mapping):
default = copy.deepcopy(default)
return salt.utils.dictupdate.update(
default,
ret,
merge_lists=opt_merge_lists)
else:
log.error(
'pillar.get: Default (%s) is a dict, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
elif isinstance(default, list):
ret = salt.utils.data.traverse_dict_and_list( # pylint: disable=redefined-variable-type
pillar_dict,
key,
[],
delimiter)
if isinstance(ret, list):
default = copy.deepcopy(default)
default.extend([x for x in ret if x not in default])
return default
else:
log.error(
'pillar.get: Default (%s) is a list, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
else:
log.error(
'pillar.get: Default (%s) is of type \'%s\', must be a dict '
'or list to merge. Merge will be skipped.',
default, type(default).__name__
)
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
default,
delimiter)
if ret is KeyError:
raise KeyError('Pillar key not found: {0}'.format(key))
return ret
|
.. versionadded:: 0.14
Attempt to retrieve the named value from :ref:`in-memory pillar data
<pillar-in-memory>`. If the pillar key is not present in the in-memory
pillar, then the value specified in the ``default`` option (described
below) will be returned.
If the merge parameter is set to ``True``, the default will be recursively
merged into the returned pillar data.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict. This means that if a dict in pillar looks like this::
{'pkg': {'apache': 'httpd'}}
To retrieve the value associated with the ``apache`` key in the ``pkg``
dict this key can be passed as::
pkg:apache
key
The pillar key to get value from
default
The value specified by this option will be returned if the desired
pillar key does not exist.
If a default value is specified, then it will be an empty string,
unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in
which case an error will be raised.
merge : ``False``
If ``True``, the retrieved values will be merged into the passed
default. When the default and the retrieved value are both
dictionaries, the dictionaries will be recursively merged.
.. versionadded:: 2014.7.0
.. versionchanged:: 2016.3.7,2016.11.4,2017.7.0
If the default and the retrieved value are not of the same type,
then merging will be skipped and the retrieved value will be
returned. Earlier releases raised an error in these cases.
merge_nested_lists
If set to ``False``, lists nested within the retrieved pillar
dictionary will *overwrite* lists in ``default``. If set to ``True``,
nested lists will be *merged* into lists in ``default``. If unspecified
(the default), this option is inherited from the
:conf_minion:`pillar_merge_lists` minion config option.
.. note::
This option is ignored when ``merge`` is set to ``False``.
.. versionadded:: 2016.11.6
delimiter
Specify an alternate delimiter to use when traversing a nested dict.
This is useful for when the desired key contains a colon. See CLI
example below for usage.
.. versionadded:: 2014.7.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.0
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' pillar.get pkg:apache
salt '*' pillar.get abc::def|ghi delimiter='|'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pillar.py#L32-L189
|
[
"def items(*args, **kwargs):\n '''\n Calls the master for a fresh pillar and generates the pillar data on the\n fly\n\n Contrast with :py:func:`raw` which returns the pillar data that is\n currently loaded into the minion.\n\n pillar\n If specified, allows for a dictionary of pillar data to be made\n available to pillar and ext_pillar rendering. these pillar variables\n will also override any variables of the same name in pillar or\n ext_pillar.\n\n .. versionadded:: 2015.5.0\n\n pillar_enc\n If specified, the data passed in the ``pillar`` argument will be passed\n through this renderer to decrypt it.\n\n .. note::\n This will decrypt on the minion side, so the specified renderer\n must be set up on the minion for this to work. Alternatively,\n pillar data can be decrypted master-side. For more information, see\n the :ref:`Pillar Encryption <pillar-encryption>` documentation.\n Pillar data that is decrypted master-side, is not decrypted until\n the end of pillar compilation though, so minion-side decryption\n will be necessary if the encrypted pillar data must be made\n available in an decrypted state pillar/ext_pillar rendering.\n\n .. versionadded:: 2017.7.0\n\n pillarenv\n Pass a specific pillar environment from which to compile pillar data.\n If not specified, then the minion's :conf_minion:`pillarenv` option is\n not used, and if that also is not specified then all configured pillar\n environments will be merged into a single pillar dictionary and\n returned.\n\n .. versionadded:: 2016.11.2\n\n saltenv\n Included only for compatibility with\n :conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pillar.items\n '''\n # Preserve backwards compatibility\n if args:\n return item(*args)\n\n pillarenv = kwargs.get('pillarenv')\n if pillarenv is None:\n if __opts__.get('pillarenv_from_saltenv', False):\n pillarenv = kwargs.get('saltenv') or __opts__['saltenv']\n else:\n pillarenv = __opts__['pillarenv']\n\n pillar_override = kwargs.get('pillar')\n pillar_enc = kwargs.get('pillar_enc')\n\n if pillar_override and pillar_enc:\n try:\n pillar_override = salt.utils.crypt.decrypt(\n pillar_override,\n pillar_enc,\n translate_newlines=True,\n opts=__opts__,\n valid_rend=__opts__['decrypt_pillar_renderers'])\n except Exception as exc:\n raise CommandExecutionError(\n 'Failed to decrypt pillar override: {0}'.format(exc)\n )\n\n pillar = salt.pillar.get_pillar(\n __opts__,\n __grains__,\n __opts__['id'],\n pillar_override=pillar_override,\n pillarenv=pillarenv)\n\n return pillar.compile_pillar()\n"
] |
# -*- coding: utf-8 -*-
'''
Extract the pillar data for this minion
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import collections
# Import third party libs
import copy
import os
import logging
from salt.ext import six
# Import salt libs
import salt.pillar
import salt.utils.crypt
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.functools
import salt.utils.odict
import salt.utils.yaml
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import CommandExecutionError
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def items(*args, **kwargs):
'''
Calls the master for a fresh pillar and generates the pillar data on the
fly
Contrast with :py:func:`raw` which returns the pillar data that is
currently loaded into the minion.
pillar
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. these pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
pillar_enc
If specified, the data passed in the ``pillar`` argument will be passed
through this renderer to decrypt it.
.. note::
This will decrypt on the minion side, so the specified renderer
must be set up on the minion for this to work. Alternatively,
pillar data can be decrypted master-side. For more information, see
the :ref:`Pillar Encryption <pillar-encryption>` documentation.
Pillar data that is decrypted master-side, is not decrypted until
the end of pillar compilation though, so minion-side decryption
will be necessary if the encrypted pillar data must be made
available in an decrypted state pillar/ext_pillar rendering.
.. versionadded:: 2017.7.0
pillarenv
Pass a specific pillar environment from which to compile pillar data.
If not specified, then the minion's :conf_minion:`pillarenv` option is
not used, and if that also is not specified then all configured pillar
environments will be merged into a single pillar dictionary and
returned.
.. versionadded:: 2016.11.2
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
CLI Example:
.. code-block:: bash
salt '*' pillar.items
'''
# Preserve backwards compatibility
if args:
return item(*args)
pillarenv = kwargs.get('pillarenv')
if pillarenv is None:
if __opts__.get('pillarenv_from_saltenv', False):
pillarenv = kwargs.get('saltenv') or __opts__['saltenv']
else:
pillarenv = __opts__['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_override and pillar_enc:
try:
pillar_override = salt.utils.crypt.decrypt(
pillar_override,
pillar_enc,
translate_newlines=True,
opts=__opts__,
valid_rend=__opts__['decrypt_pillar_renderers'])
except Exception as exc:
raise CommandExecutionError(
'Failed to decrypt pillar override: {0}'.format(exc)
)
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
pillar_override=pillar_override,
pillarenv=pillarenv)
return pillar.compile_pillar()
# Allow pillar.data to also be used to return pillar data
data = salt.utils.functools.alias_function(items, 'data')
def _obfuscate_inner(var):
'''
Recursive obfuscation of collection types.
Leaf or unknown Python types get replaced by the type name
Known collection types trigger recursion.
In the special case of mapping types, keys are not obfuscated
'''
if isinstance(var, (dict, salt.utils.odict.OrderedDict)):
return var.__class__((key, _obfuscate_inner(val))
for key, val in six.iteritems(var))
elif isinstance(var, (list, set, tuple)):
return type(var)(_obfuscate_inner(v) for v in var)
else:
return '<{0}>'.format(var.__class__.__name__)
def obfuscate(*args):
'''
.. versionadded:: 2015.8.0
Same as :py:func:`items`, but replace pillar values with a simple type indication.
This is useful to avoid displaying sensitive information on console or
flooding the console with long output, such as certificates.
For many debug or control purposes, the stakes lie more in dispatching than in
actual values.
In case the value is itself a collection type, obfuscation occurs within the value.
For mapping types, keys are not obfuscated.
Here are some examples:
* ``'secret password'`` becomes ``'<str>'``
* ``['secret', 1]`` becomes ``['<str>', '<int>']``
* ``{'login': 'somelogin', 'pwd': 'secret'}`` becomes
``{'login': '<str>', 'pwd': '<str>'}``
CLI Examples:
.. code-block:: bash
salt '*' pillar.obfuscate
'''
return _obfuscate_inner(items(*args))
# naming chosen for consistency with grains.ls, although it breaks the short
# identifier rule.
def ls(*args):
'''
.. versionadded:: 2015.8.0
Calls the master for a fresh pillar, generates the pillar data on the
fly (same as :py:func:`items`), but only shows the available main keys.
CLI Examples:
.. code-block:: bash
salt '*' pillar.ls
'''
return list(items(*args))
def item(*args, **kwargs):
'''
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
<salt.modules.pillar.get>` in that no default value can be
specified. :py:func:`pillar.get <salt.modules.pillar.get>` should
probably still be used in most cases to retrieve nested pillar
values, as it is a bit more flexible. One reason to use this
function instead of :py:func:`pillar.get <salt.modules.pillar.get>`
however is when it is desirable to retrieve the values of more than
one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can
only retrieve one key at a time.
.. versionadded:: 2015.8.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.6,2018.3.1
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.6,2018.3.1
CLI Examples:
.. code-block:: bash
salt '*' pillar.item foo
salt '*' pillar.item foo:bar
salt '*' pillar.item foo bar baz
'''
ret = {}
default = kwargs.get('default', '')
delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM)
pillarenv = kwargs.get('pillarenv', None)
saltenv = kwargs.get('saltenv', None)
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
try:
for arg in args:
ret[arg] = salt.utils.data.traverse_dict_and_list(
pillar_dict,
arg,
default,
delimiter)
except KeyError:
pass
return ret
def raw(key=None):
'''
Return the raw pillar data that is currently loaded into the minion.
Contrast with :py:func:`items` which calls the master to fetch the most
up-to-date Pillar.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw data.::
salt '*' pillar.raw key='roles'
'''
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
def ext(external, pillar=None):
'''
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single ext_pillar to add to the ext_pillar configuration. This must
be passed as a single section from the ext_pillar configuration (see
CLI examples below). For more complicated ``ext_pillar``
configurations, it can be helpful to use the Python shell to load YAML
configuration into a dictionary, and figure out
.. code-block:: python
>>> import salt.utils.yaml
>>> ext_pillar = salt.utils.yaml.safe_load("""
... ext_pillar:
... - git:
... - issue38440 https://github.com/terminalmage/git_pillar:
... - env: base
... """)
>>> ext_pillar
{'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]}
>>> ext_pillar['ext_pillar'][0]
{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}
In the above example, the value to pass would be
``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``.
Note that this would need to be quoted when passing on the CLI (as in
the CLI examples below).
pillar : None
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. These pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' pillar.ext '{libvirt: _}'
salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}"
salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}"
'''
if isinstance(external, six.string_types):
external = salt.utils.yaml.safe_load(external)
pillar_obj = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
ext=external,
pillar_override=pillar)
ret = pillar_obj.compile_pillar()
return ret
def keys(key, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2015.8.0
Attempt to retrieve a list of keys from the named value from the pillar.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict, similar to how pillar.get works.
delimiter
Specify an alternate delimiter to use when traversing a nested dict
CLI Example:
.. code-block:: bash
salt '*' pillar.keys web:sites
'''
ret = salt.utils.data.traverse_dict_and_list(
__pillar__, key, KeyError, delimiter)
if ret is KeyError:
raise KeyError("Pillar key not found: {0}".format(key))
if not isinstance(ret, dict):
raise ValueError("Pillar value in key {0} is not a dict".format(key))
return list(ret)
def file_exists(path, saltenv=None):
'''
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
'''
pillar_roots = __opts__.get('pillar_roots')
if not pillar_roots:
raise CommandExecutionError('No pillar_roots found. Are you running '
'this on the master?')
if saltenv:
if saltenv in pillar_roots:
pillar_roots = {saltenv: pillar_roots[saltenv]}
else:
return False
for env in pillar_roots:
for pillar_dir in pillar_roots[env]:
full_path = os.path.join(pillar_dir, path)
if __salt__['file.file_exists'](full_path):
return True
return False
# Provide a jinja function call compatible get aliased as fetch
fetch = get
def filter_by(lookup_dict,
pillar,
merge=None,
default='default',
base=None):
'''
.. versionadded:: 2017.7.0
Look up the given pillar in a given dictionary and return the result
:param lookup_dict: A dictionary, keyed by a pillar, containing a value or
values relevant to systems matching that pillar. For example, a key
could be a pillar for a role and the value could the name of a package
on that particular OS.
The dictionary key can be a globbing pattern. The function will return
the corresponding ``lookup_dict`` value where the pillar value matches
the pattern. For example:
.. code-block:: bash
# this will render 'got some salt' if ``role`` begins with 'salt'
salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role
:param pillar: The name of a pillar to match with the system's pillar. For
example, the value of the "role" pillar could be used to pull values
from the ``lookup_dict`` dictionary.
The pillar value can be a list. The function will return the
``lookup_dict`` value for a first found item in the list matching
one of the ``lookup_dict`` keys.
:param merge: A dictionary to merge with the results of the pillar
selection from ``lookup_dict``. This allows another dictionary to
override the values in the ``lookup_dict``.
:param default: default lookup_dict's key used if the pillar does not exist
or if the pillar value has no match on lookup_dict. If unspecified
the value is "default".
:param base: A lookup_dict key to use for a base dictionary. The
pillar-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the pillar
selection dictionary and the merge dictionary. Default is unset.
CLI Example:
.. code-block:: bash
salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role
'''
return salt.utils.data.filter_by(lookup_dict=lookup_dict,
lookup=pillar,
traverse=__pillar__,
merge=merge,
default=default,
base=base)
|
saltstack/salt
|
salt/modules/pillar.py
|
items
|
python
|
def items(*args, **kwargs):
'''
Calls the master for a fresh pillar and generates the pillar data on the
fly
Contrast with :py:func:`raw` which returns the pillar data that is
currently loaded into the minion.
pillar
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. these pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
pillar_enc
If specified, the data passed in the ``pillar`` argument will be passed
through this renderer to decrypt it.
.. note::
This will decrypt on the minion side, so the specified renderer
must be set up on the minion for this to work. Alternatively,
pillar data can be decrypted master-side. For more information, see
the :ref:`Pillar Encryption <pillar-encryption>` documentation.
Pillar data that is decrypted master-side, is not decrypted until
the end of pillar compilation though, so minion-side decryption
will be necessary if the encrypted pillar data must be made
available in an decrypted state pillar/ext_pillar rendering.
.. versionadded:: 2017.7.0
pillarenv
Pass a specific pillar environment from which to compile pillar data.
If not specified, then the minion's :conf_minion:`pillarenv` option is
not used, and if that also is not specified then all configured pillar
environments will be merged into a single pillar dictionary and
returned.
.. versionadded:: 2016.11.2
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
CLI Example:
.. code-block:: bash
salt '*' pillar.items
'''
# Preserve backwards compatibility
if args:
return item(*args)
pillarenv = kwargs.get('pillarenv')
if pillarenv is None:
if __opts__.get('pillarenv_from_saltenv', False):
pillarenv = kwargs.get('saltenv') or __opts__['saltenv']
else:
pillarenv = __opts__['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_override and pillar_enc:
try:
pillar_override = salt.utils.crypt.decrypt(
pillar_override,
pillar_enc,
translate_newlines=True,
opts=__opts__,
valid_rend=__opts__['decrypt_pillar_renderers'])
except Exception as exc:
raise CommandExecutionError(
'Failed to decrypt pillar override: {0}'.format(exc)
)
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
pillar_override=pillar_override,
pillarenv=pillarenv)
return pillar.compile_pillar()
|
Calls the master for a fresh pillar and generates the pillar data on the
fly
Contrast with :py:func:`raw` which returns the pillar data that is
currently loaded into the minion.
pillar
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. these pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
pillar_enc
If specified, the data passed in the ``pillar`` argument will be passed
through this renderer to decrypt it.
.. note::
This will decrypt on the minion side, so the specified renderer
must be set up on the minion for this to work. Alternatively,
pillar data can be decrypted master-side. For more information, see
the :ref:`Pillar Encryption <pillar-encryption>` documentation.
Pillar data that is decrypted master-side, is not decrypted until
the end of pillar compilation though, so minion-side decryption
will be necessary if the encrypted pillar data must be made
available in an decrypted state pillar/ext_pillar rendering.
.. versionadded:: 2017.7.0
pillarenv
Pass a specific pillar environment from which to compile pillar data.
If not specified, then the minion's :conf_minion:`pillarenv` option is
not used, and if that also is not specified then all configured pillar
environments will be merged into a single pillar dictionary and
returned.
.. versionadded:: 2016.11.2
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
CLI Example:
.. code-block:: bash
salt '*' pillar.items
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pillar.py#L192-L277
|
[
"def item(*args, **kwargs):\n '''\n .. versionadded:: 0.16.2\n\n Return one or more pillar entries from the :ref:`in-memory pillar data\n <pillar-in-memory>`.\n\n delimiter\n Delimiter used to traverse nested dictionaries.\n\n .. note::\n This is different from :py:func:`pillar.get\n <salt.modules.pillar.get>` in that no default value can be\n specified. :py:func:`pillar.get <salt.modules.pillar.get>` should\n probably still be used in most cases to retrieve nested pillar\n values, as it is a bit more flexible. One reason to use this\n function instead of :py:func:`pillar.get <salt.modules.pillar.get>`\n however is when it is desirable to retrieve the values of more than\n one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can\n only retrieve one key at a time.\n\n .. versionadded:: 2015.8.0\n\n pillarenv\n If specified, this function will query the master to generate fresh\n pillar data on the fly, specifically from the requested pillar\n environment. Note that this can produce different pillar data than\n executing this function without an environment, as its normal behavior\n is just to return a value from minion's pillar data in memory (which\n can be sourced from more than one pillar environment).\n\n Using this argument will not affect the pillar data in memory. It will\n however be slightly slower and use more resources on the master due to\n the need for the master to generate and send the minion fresh pillar\n data. This tradeoff in performance however allows for the use case\n where pillar data is desired only from a single environment.\n\n .. versionadded:: 2017.7.6,2018.3.1\n\n saltenv\n Included only for compatibility with\n :conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.\n\n .. versionadded:: 2017.7.6,2018.3.1\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pillar.item foo\n salt '*' pillar.item foo:bar\n salt '*' pillar.item foo bar baz\n '''\n ret = {}\n default = kwargs.get('default', '')\n delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM)\n pillarenv = kwargs.get('pillarenv', None)\n saltenv = kwargs.get('saltenv', None)\n\n pillar_dict = __pillar__ \\\n if all(x is None for x in (saltenv, pillarenv)) \\\n else items(saltenv=saltenv, pillarenv=pillarenv)\n\n try:\n for arg in args:\n ret[arg] = salt.utils.data.traverse_dict_and_list(\n pillar_dict,\n arg,\n default,\n delimiter)\n except KeyError:\n pass\n\n return ret\n",
"def get_pillar(opts, grains, minion_id, saltenv=None, ext=None, funcs=None,\n pillar_override=None, pillarenv=None, extra_minion_data=None):\n '''\n Return the correct pillar driver based on the file_client option\n '''\n file_client = opts['file_client']\n if opts.get('master_type') == 'disable' and file_client == 'remote':\n file_client = 'local'\n ptype = {\n 'remote': RemotePillar,\n 'local': Pillar\n }.get(file_client, Pillar)\n # If local pillar and we're caching, run through the cache system first\n log.debug('Determining pillar cache')\n if opts['pillar_cache']:\n log.info('Compiling pillar from cache')\n log.debug('get_pillar using pillar cache with ext: %s', ext)\n return PillarCache(opts, grains, minion_id, saltenv, ext=ext, functions=funcs,\n pillar_override=pillar_override, pillarenv=pillarenv)\n return ptype(opts, grains, minion_id, saltenv, ext, functions=funcs,\n pillar_override=pillar_override, pillarenv=pillarenv,\n extra_minion_data=extra_minion_data)\n",
"def decrypt(data,\n rend,\n translate_newlines=False,\n renderers=None,\n opts=None,\n valid_rend=None):\n '''\n .. versionadded:: 2017.7.0\n\n Decrypt a data structure using the specified renderer. Written originally\n as a common codebase to handle decryption of encrypted elements within\n Pillar data, but should be flexible enough for other uses as well.\n\n Returns the decrypted result, but any decryption renderer should be\n recursively decrypting mutable types in-place, so any data structure passed\n should be automagically decrypted using this function. Immutable types\n obviously won't, so it's a good idea to check if ``data`` is hashable in\n the calling function, and replace the original value with the decrypted\n result if that is not the case. For an example of this, see\n salt.pillar.Pillar.decrypt_pillar().\n\n data\n The data to be decrypted. This can be a string of ciphertext or a data\n structure. If it is a data structure, the items in the data structure\n will be recursively decrypted.\n\n rend\n The renderer used to decrypt\n\n translate_newlines : False\n If True, then the renderer will convert a literal backslash followed by\n an 'n' into a newline before performing the decryption.\n\n renderers\n Optionally pass a loader instance containing loaded renderer functions.\n If not passed, then the ``opts`` will be required and will be used to\n invoke the loader to get the available renderers. Where possible,\n renderers should be passed to avoid the overhead of loading them here.\n\n opts\n The master/minion configuration opts. Used only if renderers are not\n passed.\n\n valid_rend\n A list containing valid renderers, used to restrict the renderers which\n this function will be allowed to use. If not passed, no restriction\n will be made.\n '''\n try:\n if valid_rend and rend not in valid_rend:\n raise SaltInvocationError(\n '\\'{0}\\' is not a valid decryption renderer. Valid choices '\n 'are: {1}'.format(rend, ', '.join(valid_rend))\n )\n except TypeError as exc:\n # SaltInvocationError inherits TypeError, so check for it first and\n # raise if needed.\n if isinstance(exc, SaltInvocationError):\n raise\n # 'valid' argument is not iterable\n log.error('Non-iterable value %s passed for valid_rend', valid_rend)\n\n if renderers is None:\n if opts is None:\n raise TypeError('opts are required')\n renderers = salt.loader.render(opts, {})\n\n rend_func = renderers.get(rend)\n if rend_func is None:\n raise SaltInvocationError(\n 'Decryption renderer \\'{0}\\' is not available'.format(rend)\n )\n\n return rend_func(data, translate_newlines=translate_newlines)\n"
] |
# -*- coding: utf-8 -*-
'''
Extract the pillar data for this minion
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import collections
# Import third party libs
import copy
import os
import logging
from salt.ext import six
# Import salt libs
import salt.pillar
import salt.utils.crypt
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.functools
import salt.utils.odict
import salt.utils.yaml
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import CommandExecutionError
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def get(key,
default=KeyError,
merge=False,
merge_nested_lists=None,
delimiter=DEFAULT_TARGET_DELIM,
pillarenv=None,
saltenv=None):
'''
.. versionadded:: 0.14
Attempt to retrieve the named value from :ref:`in-memory pillar data
<pillar-in-memory>`. If the pillar key is not present in the in-memory
pillar, then the value specified in the ``default`` option (described
below) will be returned.
If the merge parameter is set to ``True``, the default will be recursively
merged into the returned pillar data.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict. This means that if a dict in pillar looks like this::
{'pkg': {'apache': 'httpd'}}
To retrieve the value associated with the ``apache`` key in the ``pkg``
dict this key can be passed as::
pkg:apache
key
The pillar key to get value from
default
The value specified by this option will be returned if the desired
pillar key does not exist.
If a default value is specified, then it will be an empty string,
unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in
which case an error will be raised.
merge : ``False``
If ``True``, the retrieved values will be merged into the passed
default. When the default and the retrieved value are both
dictionaries, the dictionaries will be recursively merged.
.. versionadded:: 2014.7.0
.. versionchanged:: 2016.3.7,2016.11.4,2017.7.0
If the default and the retrieved value are not of the same type,
then merging will be skipped and the retrieved value will be
returned. Earlier releases raised an error in these cases.
merge_nested_lists
If set to ``False``, lists nested within the retrieved pillar
dictionary will *overwrite* lists in ``default``. If set to ``True``,
nested lists will be *merged* into lists in ``default``. If unspecified
(the default), this option is inherited from the
:conf_minion:`pillar_merge_lists` minion config option.
.. note::
This option is ignored when ``merge`` is set to ``False``.
.. versionadded:: 2016.11.6
delimiter
Specify an alternate delimiter to use when traversing a nested dict.
This is useful for when the desired key contains a colon. See CLI
example below for usage.
.. versionadded:: 2014.7.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.0
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' pillar.get pkg:apache
salt '*' pillar.get abc::def|ghi delimiter='|'
'''
if not __opts__.get('pillar_raise_on_missing'):
if default is KeyError:
default = ''
opt_merge_lists = __opts__.get('pillar_merge_lists', False) if \
merge_nested_lists is None else merge_nested_lists
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
if merge:
if isinstance(default, dict):
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
{},
delimiter)
if isinstance(ret, collections.Mapping):
default = copy.deepcopy(default)
return salt.utils.dictupdate.update(
default,
ret,
merge_lists=opt_merge_lists)
else:
log.error(
'pillar.get: Default (%s) is a dict, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
elif isinstance(default, list):
ret = salt.utils.data.traverse_dict_and_list( # pylint: disable=redefined-variable-type
pillar_dict,
key,
[],
delimiter)
if isinstance(ret, list):
default = copy.deepcopy(default)
default.extend([x for x in ret if x not in default])
return default
else:
log.error(
'pillar.get: Default (%s) is a list, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
else:
log.error(
'pillar.get: Default (%s) is of type \'%s\', must be a dict '
'or list to merge. Merge will be skipped.',
default, type(default).__name__
)
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
default,
delimiter)
if ret is KeyError:
raise KeyError('Pillar key not found: {0}'.format(key))
return ret
# Allow pillar.data to also be used to return pillar data
data = salt.utils.functools.alias_function(items, 'data')
def _obfuscate_inner(var):
'''
Recursive obfuscation of collection types.
Leaf or unknown Python types get replaced by the type name
Known collection types trigger recursion.
In the special case of mapping types, keys are not obfuscated
'''
if isinstance(var, (dict, salt.utils.odict.OrderedDict)):
return var.__class__((key, _obfuscate_inner(val))
for key, val in six.iteritems(var))
elif isinstance(var, (list, set, tuple)):
return type(var)(_obfuscate_inner(v) for v in var)
else:
return '<{0}>'.format(var.__class__.__name__)
def obfuscate(*args):
'''
.. versionadded:: 2015.8.0
Same as :py:func:`items`, but replace pillar values with a simple type indication.
This is useful to avoid displaying sensitive information on console or
flooding the console with long output, such as certificates.
For many debug or control purposes, the stakes lie more in dispatching than in
actual values.
In case the value is itself a collection type, obfuscation occurs within the value.
For mapping types, keys are not obfuscated.
Here are some examples:
* ``'secret password'`` becomes ``'<str>'``
* ``['secret', 1]`` becomes ``['<str>', '<int>']``
* ``{'login': 'somelogin', 'pwd': 'secret'}`` becomes
``{'login': '<str>', 'pwd': '<str>'}``
CLI Examples:
.. code-block:: bash
salt '*' pillar.obfuscate
'''
return _obfuscate_inner(items(*args))
# naming chosen for consistency with grains.ls, although it breaks the short
# identifier rule.
def ls(*args):
'''
.. versionadded:: 2015.8.0
Calls the master for a fresh pillar, generates the pillar data on the
fly (same as :py:func:`items`), but only shows the available main keys.
CLI Examples:
.. code-block:: bash
salt '*' pillar.ls
'''
return list(items(*args))
def item(*args, **kwargs):
'''
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
<salt.modules.pillar.get>` in that no default value can be
specified. :py:func:`pillar.get <salt.modules.pillar.get>` should
probably still be used in most cases to retrieve nested pillar
values, as it is a bit more flexible. One reason to use this
function instead of :py:func:`pillar.get <salt.modules.pillar.get>`
however is when it is desirable to retrieve the values of more than
one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can
only retrieve one key at a time.
.. versionadded:: 2015.8.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.6,2018.3.1
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.6,2018.3.1
CLI Examples:
.. code-block:: bash
salt '*' pillar.item foo
salt '*' pillar.item foo:bar
salt '*' pillar.item foo bar baz
'''
ret = {}
default = kwargs.get('default', '')
delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM)
pillarenv = kwargs.get('pillarenv', None)
saltenv = kwargs.get('saltenv', None)
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
try:
for arg in args:
ret[arg] = salt.utils.data.traverse_dict_and_list(
pillar_dict,
arg,
default,
delimiter)
except KeyError:
pass
return ret
def raw(key=None):
'''
Return the raw pillar data that is currently loaded into the minion.
Contrast with :py:func:`items` which calls the master to fetch the most
up-to-date Pillar.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw data.::
salt '*' pillar.raw key='roles'
'''
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
def ext(external, pillar=None):
'''
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single ext_pillar to add to the ext_pillar configuration. This must
be passed as a single section from the ext_pillar configuration (see
CLI examples below). For more complicated ``ext_pillar``
configurations, it can be helpful to use the Python shell to load YAML
configuration into a dictionary, and figure out
.. code-block:: python
>>> import salt.utils.yaml
>>> ext_pillar = salt.utils.yaml.safe_load("""
... ext_pillar:
... - git:
... - issue38440 https://github.com/terminalmage/git_pillar:
... - env: base
... """)
>>> ext_pillar
{'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]}
>>> ext_pillar['ext_pillar'][0]
{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}
In the above example, the value to pass would be
``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``.
Note that this would need to be quoted when passing on the CLI (as in
the CLI examples below).
pillar : None
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. These pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' pillar.ext '{libvirt: _}'
salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}"
salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}"
'''
if isinstance(external, six.string_types):
external = salt.utils.yaml.safe_load(external)
pillar_obj = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
ext=external,
pillar_override=pillar)
ret = pillar_obj.compile_pillar()
return ret
def keys(key, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2015.8.0
Attempt to retrieve a list of keys from the named value from the pillar.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict, similar to how pillar.get works.
delimiter
Specify an alternate delimiter to use when traversing a nested dict
CLI Example:
.. code-block:: bash
salt '*' pillar.keys web:sites
'''
ret = salt.utils.data.traverse_dict_and_list(
__pillar__, key, KeyError, delimiter)
if ret is KeyError:
raise KeyError("Pillar key not found: {0}".format(key))
if not isinstance(ret, dict):
raise ValueError("Pillar value in key {0} is not a dict".format(key))
return list(ret)
def file_exists(path, saltenv=None):
'''
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
'''
pillar_roots = __opts__.get('pillar_roots')
if not pillar_roots:
raise CommandExecutionError('No pillar_roots found. Are you running '
'this on the master?')
if saltenv:
if saltenv in pillar_roots:
pillar_roots = {saltenv: pillar_roots[saltenv]}
else:
return False
for env in pillar_roots:
for pillar_dir in pillar_roots[env]:
full_path = os.path.join(pillar_dir, path)
if __salt__['file.file_exists'](full_path):
return True
return False
# Provide a jinja function call compatible get aliased as fetch
fetch = get
def filter_by(lookup_dict,
pillar,
merge=None,
default='default',
base=None):
'''
.. versionadded:: 2017.7.0
Look up the given pillar in a given dictionary and return the result
:param lookup_dict: A dictionary, keyed by a pillar, containing a value or
values relevant to systems matching that pillar. For example, a key
could be a pillar for a role and the value could the name of a package
on that particular OS.
The dictionary key can be a globbing pattern. The function will return
the corresponding ``lookup_dict`` value where the pillar value matches
the pattern. For example:
.. code-block:: bash
# this will render 'got some salt' if ``role`` begins with 'salt'
salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role
:param pillar: The name of a pillar to match with the system's pillar. For
example, the value of the "role" pillar could be used to pull values
from the ``lookup_dict`` dictionary.
The pillar value can be a list. The function will return the
``lookup_dict`` value for a first found item in the list matching
one of the ``lookup_dict`` keys.
:param merge: A dictionary to merge with the results of the pillar
selection from ``lookup_dict``. This allows another dictionary to
override the values in the ``lookup_dict``.
:param default: default lookup_dict's key used if the pillar does not exist
or if the pillar value has no match on lookup_dict. If unspecified
the value is "default".
:param base: A lookup_dict key to use for a base dictionary. The
pillar-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the pillar
selection dictionary and the merge dictionary. Default is unset.
CLI Example:
.. code-block:: bash
salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role
'''
return salt.utils.data.filter_by(lookup_dict=lookup_dict,
lookup=pillar,
traverse=__pillar__,
merge=merge,
default=default,
base=base)
|
saltstack/salt
|
salt/modules/pillar.py
|
_obfuscate_inner
|
python
|
def _obfuscate_inner(var):
'''
Recursive obfuscation of collection types.
Leaf or unknown Python types get replaced by the type name
Known collection types trigger recursion.
In the special case of mapping types, keys are not obfuscated
'''
if isinstance(var, (dict, salt.utils.odict.OrderedDict)):
return var.__class__((key, _obfuscate_inner(val))
for key, val in six.iteritems(var))
elif isinstance(var, (list, set, tuple)):
return type(var)(_obfuscate_inner(v) for v in var)
else:
return '<{0}>'.format(var.__class__.__name__)
|
Recursive obfuscation of collection types.
Leaf or unknown Python types get replaced by the type name
Known collection types trigger recursion.
In the special case of mapping types, keys are not obfuscated
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pillar.py#L284-L298
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Extract the pillar data for this minion
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import collections
# Import third party libs
import copy
import os
import logging
from salt.ext import six
# Import salt libs
import salt.pillar
import salt.utils.crypt
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.functools
import salt.utils.odict
import salt.utils.yaml
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import CommandExecutionError
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def get(key,
default=KeyError,
merge=False,
merge_nested_lists=None,
delimiter=DEFAULT_TARGET_DELIM,
pillarenv=None,
saltenv=None):
'''
.. versionadded:: 0.14
Attempt to retrieve the named value from :ref:`in-memory pillar data
<pillar-in-memory>`. If the pillar key is not present in the in-memory
pillar, then the value specified in the ``default`` option (described
below) will be returned.
If the merge parameter is set to ``True``, the default will be recursively
merged into the returned pillar data.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict. This means that if a dict in pillar looks like this::
{'pkg': {'apache': 'httpd'}}
To retrieve the value associated with the ``apache`` key in the ``pkg``
dict this key can be passed as::
pkg:apache
key
The pillar key to get value from
default
The value specified by this option will be returned if the desired
pillar key does not exist.
If a default value is specified, then it will be an empty string,
unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in
which case an error will be raised.
merge : ``False``
If ``True``, the retrieved values will be merged into the passed
default. When the default and the retrieved value are both
dictionaries, the dictionaries will be recursively merged.
.. versionadded:: 2014.7.0
.. versionchanged:: 2016.3.7,2016.11.4,2017.7.0
If the default and the retrieved value are not of the same type,
then merging will be skipped and the retrieved value will be
returned. Earlier releases raised an error in these cases.
merge_nested_lists
If set to ``False``, lists nested within the retrieved pillar
dictionary will *overwrite* lists in ``default``. If set to ``True``,
nested lists will be *merged* into lists in ``default``. If unspecified
(the default), this option is inherited from the
:conf_minion:`pillar_merge_lists` minion config option.
.. note::
This option is ignored when ``merge`` is set to ``False``.
.. versionadded:: 2016.11.6
delimiter
Specify an alternate delimiter to use when traversing a nested dict.
This is useful for when the desired key contains a colon. See CLI
example below for usage.
.. versionadded:: 2014.7.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.0
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' pillar.get pkg:apache
salt '*' pillar.get abc::def|ghi delimiter='|'
'''
if not __opts__.get('pillar_raise_on_missing'):
if default is KeyError:
default = ''
opt_merge_lists = __opts__.get('pillar_merge_lists', False) if \
merge_nested_lists is None else merge_nested_lists
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
if merge:
if isinstance(default, dict):
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
{},
delimiter)
if isinstance(ret, collections.Mapping):
default = copy.deepcopy(default)
return salt.utils.dictupdate.update(
default,
ret,
merge_lists=opt_merge_lists)
else:
log.error(
'pillar.get: Default (%s) is a dict, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
elif isinstance(default, list):
ret = salt.utils.data.traverse_dict_and_list( # pylint: disable=redefined-variable-type
pillar_dict,
key,
[],
delimiter)
if isinstance(ret, list):
default = copy.deepcopy(default)
default.extend([x for x in ret if x not in default])
return default
else:
log.error(
'pillar.get: Default (%s) is a list, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
else:
log.error(
'pillar.get: Default (%s) is of type \'%s\', must be a dict '
'or list to merge. Merge will be skipped.',
default, type(default).__name__
)
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
default,
delimiter)
if ret is KeyError:
raise KeyError('Pillar key not found: {0}'.format(key))
return ret
def items(*args, **kwargs):
'''
Calls the master for a fresh pillar and generates the pillar data on the
fly
Contrast with :py:func:`raw` which returns the pillar data that is
currently loaded into the minion.
pillar
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. these pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
pillar_enc
If specified, the data passed in the ``pillar`` argument will be passed
through this renderer to decrypt it.
.. note::
This will decrypt on the minion side, so the specified renderer
must be set up on the minion for this to work. Alternatively,
pillar data can be decrypted master-side. For more information, see
the :ref:`Pillar Encryption <pillar-encryption>` documentation.
Pillar data that is decrypted master-side, is not decrypted until
the end of pillar compilation though, so minion-side decryption
will be necessary if the encrypted pillar data must be made
available in an decrypted state pillar/ext_pillar rendering.
.. versionadded:: 2017.7.0
pillarenv
Pass a specific pillar environment from which to compile pillar data.
If not specified, then the minion's :conf_minion:`pillarenv` option is
not used, and if that also is not specified then all configured pillar
environments will be merged into a single pillar dictionary and
returned.
.. versionadded:: 2016.11.2
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
CLI Example:
.. code-block:: bash
salt '*' pillar.items
'''
# Preserve backwards compatibility
if args:
return item(*args)
pillarenv = kwargs.get('pillarenv')
if pillarenv is None:
if __opts__.get('pillarenv_from_saltenv', False):
pillarenv = kwargs.get('saltenv') or __opts__['saltenv']
else:
pillarenv = __opts__['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_override and pillar_enc:
try:
pillar_override = salt.utils.crypt.decrypt(
pillar_override,
pillar_enc,
translate_newlines=True,
opts=__opts__,
valid_rend=__opts__['decrypt_pillar_renderers'])
except Exception as exc:
raise CommandExecutionError(
'Failed to decrypt pillar override: {0}'.format(exc)
)
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
pillar_override=pillar_override,
pillarenv=pillarenv)
return pillar.compile_pillar()
# Allow pillar.data to also be used to return pillar data
data = salt.utils.functools.alias_function(items, 'data')
def obfuscate(*args):
'''
.. versionadded:: 2015.8.0
Same as :py:func:`items`, but replace pillar values with a simple type indication.
This is useful to avoid displaying sensitive information on console or
flooding the console with long output, such as certificates.
For many debug or control purposes, the stakes lie more in dispatching than in
actual values.
In case the value is itself a collection type, obfuscation occurs within the value.
For mapping types, keys are not obfuscated.
Here are some examples:
* ``'secret password'`` becomes ``'<str>'``
* ``['secret', 1]`` becomes ``['<str>', '<int>']``
* ``{'login': 'somelogin', 'pwd': 'secret'}`` becomes
``{'login': '<str>', 'pwd': '<str>'}``
CLI Examples:
.. code-block:: bash
salt '*' pillar.obfuscate
'''
return _obfuscate_inner(items(*args))
# naming chosen for consistency with grains.ls, although it breaks the short
# identifier rule.
def ls(*args):
'''
.. versionadded:: 2015.8.0
Calls the master for a fresh pillar, generates the pillar data on the
fly (same as :py:func:`items`), but only shows the available main keys.
CLI Examples:
.. code-block:: bash
salt '*' pillar.ls
'''
return list(items(*args))
def item(*args, **kwargs):
'''
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
<salt.modules.pillar.get>` in that no default value can be
specified. :py:func:`pillar.get <salt.modules.pillar.get>` should
probably still be used in most cases to retrieve nested pillar
values, as it is a bit more flexible. One reason to use this
function instead of :py:func:`pillar.get <salt.modules.pillar.get>`
however is when it is desirable to retrieve the values of more than
one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can
only retrieve one key at a time.
.. versionadded:: 2015.8.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.6,2018.3.1
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.6,2018.3.1
CLI Examples:
.. code-block:: bash
salt '*' pillar.item foo
salt '*' pillar.item foo:bar
salt '*' pillar.item foo bar baz
'''
ret = {}
default = kwargs.get('default', '')
delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM)
pillarenv = kwargs.get('pillarenv', None)
saltenv = kwargs.get('saltenv', None)
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
try:
for arg in args:
ret[arg] = salt.utils.data.traverse_dict_and_list(
pillar_dict,
arg,
default,
delimiter)
except KeyError:
pass
return ret
def raw(key=None):
'''
Return the raw pillar data that is currently loaded into the minion.
Contrast with :py:func:`items` which calls the master to fetch the most
up-to-date Pillar.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw data.::
salt '*' pillar.raw key='roles'
'''
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
def ext(external, pillar=None):
'''
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single ext_pillar to add to the ext_pillar configuration. This must
be passed as a single section from the ext_pillar configuration (see
CLI examples below). For more complicated ``ext_pillar``
configurations, it can be helpful to use the Python shell to load YAML
configuration into a dictionary, and figure out
.. code-block:: python
>>> import salt.utils.yaml
>>> ext_pillar = salt.utils.yaml.safe_load("""
... ext_pillar:
... - git:
... - issue38440 https://github.com/terminalmage/git_pillar:
... - env: base
... """)
>>> ext_pillar
{'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]}
>>> ext_pillar['ext_pillar'][0]
{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}
In the above example, the value to pass would be
``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``.
Note that this would need to be quoted when passing on the CLI (as in
the CLI examples below).
pillar : None
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. These pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' pillar.ext '{libvirt: _}'
salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}"
salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}"
'''
if isinstance(external, six.string_types):
external = salt.utils.yaml.safe_load(external)
pillar_obj = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
ext=external,
pillar_override=pillar)
ret = pillar_obj.compile_pillar()
return ret
def keys(key, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2015.8.0
Attempt to retrieve a list of keys from the named value from the pillar.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict, similar to how pillar.get works.
delimiter
Specify an alternate delimiter to use when traversing a nested dict
CLI Example:
.. code-block:: bash
salt '*' pillar.keys web:sites
'''
ret = salt.utils.data.traverse_dict_and_list(
__pillar__, key, KeyError, delimiter)
if ret is KeyError:
raise KeyError("Pillar key not found: {0}".format(key))
if not isinstance(ret, dict):
raise ValueError("Pillar value in key {0} is not a dict".format(key))
return list(ret)
def file_exists(path, saltenv=None):
'''
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
'''
pillar_roots = __opts__.get('pillar_roots')
if not pillar_roots:
raise CommandExecutionError('No pillar_roots found. Are you running '
'this on the master?')
if saltenv:
if saltenv in pillar_roots:
pillar_roots = {saltenv: pillar_roots[saltenv]}
else:
return False
for env in pillar_roots:
for pillar_dir in pillar_roots[env]:
full_path = os.path.join(pillar_dir, path)
if __salt__['file.file_exists'](full_path):
return True
return False
# Provide a jinja function call compatible get aliased as fetch
fetch = get
def filter_by(lookup_dict,
pillar,
merge=None,
default='default',
base=None):
'''
.. versionadded:: 2017.7.0
Look up the given pillar in a given dictionary and return the result
:param lookup_dict: A dictionary, keyed by a pillar, containing a value or
values relevant to systems matching that pillar. For example, a key
could be a pillar for a role and the value could the name of a package
on that particular OS.
The dictionary key can be a globbing pattern. The function will return
the corresponding ``lookup_dict`` value where the pillar value matches
the pattern. For example:
.. code-block:: bash
# this will render 'got some salt' if ``role`` begins with 'salt'
salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role
:param pillar: The name of a pillar to match with the system's pillar. For
example, the value of the "role" pillar could be used to pull values
from the ``lookup_dict`` dictionary.
The pillar value can be a list. The function will return the
``lookup_dict`` value for a first found item in the list matching
one of the ``lookup_dict`` keys.
:param merge: A dictionary to merge with the results of the pillar
selection from ``lookup_dict``. This allows another dictionary to
override the values in the ``lookup_dict``.
:param default: default lookup_dict's key used if the pillar does not exist
or if the pillar value has no match on lookup_dict. If unspecified
the value is "default".
:param base: A lookup_dict key to use for a base dictionary. The
pillar-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the pillar
selection dictionary and the merge dictionary. Default is unset.
CLI Example:
.. code-block:: bash
salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role
'''
return salt.utils.data.filter_by(lookup_dict=lookup_dict,
lookup=pillar,
traverse=__pillar__,
merge=merge,
default=default,
base=base)
|
saltstack/salt
|
salt/modules/pillar.py
|
item
|
python
|
def item(*args, **kwargs):
'''
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
<salt.modules.pillar.get>` in that no default value can be
specified. :py:func:`pillar.get <salt.modules.pillar.get>` should
probably still be used in most cases to retrieve nested pillar
values, as it is a bit more flexible. One reason to use this
function instead of :py:func:`pillar.get <salt.modules.pillar.get>`
however is when it is desirable to retrieve the values of more than
one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can
only retrieve one key at a time.
.. versionadded:: 2015.8.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.6,2018.3.1
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.6,2018.3.1
CLI Examples:
.. code-block:: bash
salt '*' pillar.item foo
salt '*' pillar.item foo:bar
salt '*' pillar.item foo bar baz
'''
ret = {}
default = kwargs.get('default', '')
delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM)
pillarenv = kwargs.get('pillarenv', None)
saltenv = kwargs.get('saltenv', None)
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
try:
for arg in args:
ret[arg] = salt.utils.data.traverse_dict_and_list(
pillar_dict,
arg,
default,
delimiter)
except KeyError:
pass
return ret
|
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
<salt.modules.pillar.get>` in that no default value can be
specified. :py:func:`pillar.get <salt.modules.pillar.get>` should
probably still be used in most cases to retrieve nested pillar
values, as it is a bit more flexible. One reason to use this
function instead of :py:func:`pillar.get <salt.modules.pillar.get>`
however is when it is desirable to retrieve the values of more than
one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can
only retrieve one key at a time.
.. versionadded:: 2015.8.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.6,2018.3.1
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.6,2018.3.1
CLI Examples:
.. code-block:: bash
salt '*' pillar.item foo
salt '*' pillar.item foo:bar
salt '*' pillar.item foo bar baz
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pillar.py#L350-L423
|
[
"def items(*args, **kwargs):\n '''\n Calls the master for a fresh pillar and generates the pillar data on the\n fly\n\n Contrast with :py:func:`raw` which returns the pillar data that is\n currently loaded into the minion.\n\n pillar\n If specified, allows for a dictionary of pillar data to be made\n available to pillar and ext_pillar rendering. these pillar variables\n will also override any variables of the same name in pillar or\n ext_pillar.\n\n .. versionadded:: 2015.5.0\n\n pillar_enc\n If specified, the data passed in the ``pillar`` argument will be passed\n through this renderer to decrypt it.\n\n .. note::\n This will decrypt on the minion side, so the specified renderer\n must be set up on the minion for this to work. Alternatively,\n pillar data can be decrypted master-side. For more information, see\n the :ref:`Pillar Encryption <pillar-encryption>` documentation.\n Pillar data that is decrypted master-side, is not decrypted until\n the end of pillar compilation though, so minion-side decryption\n will be necessary if the encrypted pillar data must be made\n available in an decrypted state pillar/ext_pillar rendering.\n\n .. versionadded:: 2017.7.0\n\n pillarenv\n Pass a specific pillar environment from which to compile pillar data.\n If not specified, then the minion's :conf_minion:`pillarenv` option is\n not used, and if that also is not specified then all configured pillar\n environments will be merged into a single pillar dictionary and\n returned.\n\n .. versionadded:: 2016.11.2\n\n saltenv\n Included only for compatibility with\n :conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pillar.items\n '''\n # Preserve backwards compatibility\n if args:\n return item(*args)\n\n pillarenv = kwargs.get('pillarenv')\n if pillarenv is None:\n if __opts__.get('pillarenv_from_saltenv', False):\n pillarenv = kwargs.get('saltenv') or __opts__['saltenv']\n else:\n pillarenv = __opts__['pillarenv']\n\n pillar_override = kwargs.get('pillar')\n pillar_enc = kwargs.get('pillar_enc')\n\n if pillar_override and pillar_enc:\n try:\n pillar_override = salt.utils.crypt.decrypt(\n pillar_override,\n pillar_enc,\n translate_newlines=True,\n opts=__opts__,\n valid_rend=__opts__['decrypt_pillar_renderers'])\n except Exception as exc:\n raise CommandExecutionError(\n 'Failed to decrypt pillar override: {0}'.format(exc)\n )\n\n pillar = salt.pillar.get_pillar(\n __opts__,\n __grains__,\n __opts__['id'],\n pillar_override=pillar_override,\n pillarenv=pillarenv)\n\n return pillar.compile_pillar()\n"
] |
# -*- coding: utf-8 -*-
'''
Extract the pillar data for this minion
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import collections
# Import third party libs
import copy
import os
import logging
from salt.ext import six
# Import salt libs
import salt.pillar
import salt.utils.crypt
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.functools
import salt.utils.odict
import salt.utils.yaml
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import CommandExecutionError
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def get(key,
default=KeyError,
merge=False,
merge_nested_lists=None,
delimiter=DEFAULT_TARGET_DELIM,
pillarenv=None,
saltenv=None):
'''
.. versionadded:: 0.14
Attempt to retrieve the named value from :ref:`in-memory pillar data
<pillar-in-memory>`. If the pillar key is not present in the in-memory
pillar, then the value specified in the ``default`` option (described
below) will be returned.
If the merge parameter is set to ``True``, the default will be recursively
merged into the returned pillar data.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict. This means that if a dict in pillar looks like this::
{'pkg': {'apache': 'httpd'}}
To retrieve the value associated with the ``apache`` key in the ``pkg``
dict this key can be passed as::
pkg:apache
key
The pillar key to get value from
default
The value specified by this option will be returned if the desired
pillar key does not exist.
If a default value is specified, then it will be an empty string,
unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in
which case an error will be raised.
merge : ``False``
If ``True``, the retrieved values will be merged into the passed
default. When the default and the retrieved value are both
dictionaries, the dictionaries will be recursively merged.
.. versionadded:: 2014.7.0
.. versionchanged:: 2016.3.7,2016.11.4,2017.7.0
If the default and the retrieved value are not of the same type,
then merging will be skipped and the retrieved value will be
returned. Earlier releases raised an error in these cases.
merge_nested_lists
If set to ``False``, lists nested within the retrieved pillar
dictionary will *overwrite* lists in ``default``. If set to ``True``,
nested lists will be *merged* into lists in ``default``. If unspecified
(the default), this option is inherited from the
:conf_minion:`pillar_merge_lists` minion config option.
.. note::
This option is ignored when ``merge`` is set to ``False``.
.. versionadded:: 2016.11.6
delimiter
Specify an alternate delimiter to use when traversing a nested dict.
This is useful for when the desired key contains a colon. See CLI
example below for usage.
.. versionadded:: 2014.7.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.0
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' pillar.get pkg:apache
salt '*' pillar.get abc::def|ghi delimiter='|'
'''
if not __opts__.get('pillar_raise_on_missing'):
if default is KeyError:
default = ''
opt_merge_lists = __opts__.get('pillar_merge_lists', False) if \
merge_nested_lists is None else merge_nested_lists
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
if merge:
if isinstance(default, dict):
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
{},
delimiter)
if isinstance(ret, collections.Mapping):
default = copy.deepcopy(default)
return salt.utils.dictupdate.update(
default,
ret,
merge_lists=opt_merge_lists)
else:
log.error(
'pillar.get: Default (%s) is a dict, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
elif isinstance(default, list):
ret = salt.utils.data.traverse_dict_and_list( # pylint: disable=redefined-variable-type
pillar_dict,
key,
[],
delimiter)
if isinstance(ret, list):
default = copy.deepcopy(default)
default.extend([x for x in ret if x not in default])
return default
else:
log.error(
'pillar.get: Default (%s) is a list, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
else:
log.error(
'pillar.get: Default (%s) is of type \'%s\', must be a dict '
'or list to merge. Merge will be skipped.',
default, type(default).__name__
)
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
default,
delimiter)
if ret is KeyError:
raise KeyError('Pillar key not found: {0}'.format(key))
return ret
def items(*args, **kwargs):
'''
Calls the master for a fresh pillar and generates the pillar data on the
fly
Contrast with :py:func:`raw` which returns the pillar data that is
currently loaded into the minion.
pillar
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. these pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
pillar_enc
If specified, the data passed in the ``pillar`` argument will be passed
through this renderer to decrypt it.
.. note::
This will decrypt on the minion side, so the specified renderer
must be set up on the minion for this to work. Alternatively,
pillar data can be decrypted master-side. For more information, see
the :ref:`Pillar Encryption <pillar-encryption>` documentation.
Pillar data that is decrypted master-side, is not decrypted until
the end of pillar compilation though, so minion-side decryption
will be necessary if the encrypted pillar data must be made
available in an decrypted state pillar/ext_pillar rendering.
.. versionadded:: 2017.7.0
pillarenv
Pass a specific pillar environment from which to compile pillar data.
If not specified, then the minion's :conf_minion:`pillarenv` option is
not used, and if that also is not specified then all configured pillar
environments will be merged into a single pillar dictionary and
returned.
.. versionadded:: 2016.11.2
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
CLI Example:
.. code-block:: bash
salt '*' pillar.items
'''
# Preserve backwards compatibility
if args:
return item(*args)
pillarenv = kwargs.get('pillarenv')
if pillarenv is None:
if __opts__.get('pillarenv_from_saltenv', False):
pillarenv = kwargs.get('saltenv') or __opts__['saltenv']
else:
pillarenv = __opts__['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_override and pillar_enc:
try:
pillar_override = salt.utils.crypt.decrypt(
pillar_override,
pillar_enc,
translate_newlines=True,
opts=__opts__,
valid_rend=__opts__['decrypt_pillar_renderers'])
except Exception as exc:
raise CommandExecutionError(
'Failed to decrypt pillar override: {0}'.format(exc)
)
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
pillar_override=pillar_override,
pillarenv=pillarenv)
return pillar.compile_pillar()
# Allow pillar.data to also be used to return pillar data
data = salt.utils.functools.alias_function(items, 'data')
def _obfuscate_inner(var):
'''
Recursive obfuscation of collection types.
Leaf or unknown Python types get replaced by the type name
Known collection types trigger recursion.
In the special case of mapping types, keys are not obfuscated
'''
if isinstance(var, (dict, salt.utils.odict.OrderedDict)):
return var.__class__((key, _obfuscate_inner(val))
for key, val in six.iteritems(var))
elif isinstance(var, (list, set, tuple)):
return type(var)(_obfuscate_inner(v) for v in var)
else:
return '<{0}>'.format(var.__class__.__name__)
def obfuscate(*args):
'''
.. versionadded:: 2015.8.0
Same as :py:func:`items`, but replace pillar values with a simple type indication.
This is useful to avoid displaying sensitive information on console or
flooding the console with long output, such as certificates.
For many debug or control purposes, the stakes lie more in dispatching than in
actual values.
In case the value is itself a collection type, obfuscation occurs within the value.
For mapping types, keys are not obfuscated.
Here are some examples:
* ``'secret password'`` becomes ``'<str>'``
* ``['secret', 1]`` becomes ``['<str>', '<int>']``
* ``{'login': 'somelogin', 'pwd': 'secret'}`` becomes
``{'login': '<str>', 'pwd': '<str>'}``
CLI Examples:
.. code-block:: bash
salt '*' pillar.obfuscate
'''
return _obfuscate_inner(items(*args))
# naming chosen for consistency with grains.ls, although it breaks the short
# identifier rule.
def ls(*args):
'''
.. versionadded:: 2015.8.0
Calls the master for a fresh pillar, generates the pillar data on the
fly (same as :py:func:`items`), but only shows the available main keys.
CLI Examples:
.. code-block:: bash
salt '*' pillar.ls
'''
return list(items(*args))
def raw(key=None):
'''
Return the raw pillar data that is currently loaded into the minion.
Contrast with :py:func:`items` which calls the master to fetch the most
up-to-date Pillar.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw data.::
salt '*' pillar.raw key='roles'
'''
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
def ext(external, pillar=None):
'''
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single ext_pillar to add to the ext_pillar configuration. This must
be passed as a single section from the ext_pillar configuration (see
CLI examples below). For more complicated ``ext_pillar``
configurations, it can be helpful to use the Python shell to load YAML
configuration into a dictionary, and figure out
.. code-block:: python
>>> import salt.utils.yaml
>>> ext_pillar = salt.utils.yaml.safe_load("""
... ext_pillar:
... - git:
... - issue38440 https://github.com/terminalmage/git_pillar:
... - env: base
... """)
>>> ext_pillar
{'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]}
>>> ext_pillar['ext_pillar'][0]
{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}
In the above example, the value to pass would be
``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``.
Note that this would need to be quoted when passing on the CLI (as in
the CLI examples below).
pillar : None
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. These pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' pillar.ext '{libvirt: _}'
salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}"
salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}"
'''
if isinstance(external, six.string_types):
external = salt.utils.yaml.safe_load(external)
pillar_obj = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
ext=external,
pillar_override=pillar)
ret = pillar_obj.compile_pillar()
return ret
def keys(key, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2015.8.0
Attempt to retrieve a list of keys from the named value from the pillar.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict, similar to how pillar.get works.
delimiter
Specify an alternate delimiter to use when traversing a nested dict
CLI Example:
.. code-block:: bash
salt '*' pillar.keys web:sites
'''
ret = salt.utils.data.traverse_dict_and_list(
__pillar__, key, KeyError, delimiter)
if ret is KeyError:
raise KeyError("Pillar key not found: {0}".format(key))
if not isinstance(ret, dict):
raise ValueError("Pillar value in key {0} is not a dict".format(key))
return list(ret)
def file_exists(path, saltenv=None):
'''
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
'''
pillar_roots = __opts__.get('pillar_roots')
if not pillar_roots:
raise CommandExecutionError('No pillar_roots found. Are you running '
'this on the master?')
if saltenv:
if saltenv in pillar_roots:
pillar_roots = {saltenv: pillar_roots[saltenv]}
else:
return False
for env in pillar_roots:
for pillar_dir in pillar_roots[env]:
full_path = os.path.join(pillar_dir, path)
if __salt__['file.file_exists'](full_path):
return True
return False
# Provide a jinja function call compatible get aliased as fetch
fetch = get
def filter_by(lookup_dict,
pillar,
merge=None,
default='default',
base=None):
'''
.. versionadded:: 2017.7.0
Look up the given pillar in a given dictionary and return the result
:param lookup_dict: A dictionary, keyed by a pillar, containing a value or
values relevant to systems matching that pillar. For example, a key
could be a pillar for a role and the value could the name of a package
on that particular OS.
The dictionary key can be a globbing pattern. The function will return
the corresponding ``lookup_dict`` value where the pillar value matches
the pattern. For example:
.. code-block:: bash
# this will render 'got some salt' if ``role`` begins with 'salt'
salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role
:param pillar: The name of a pillar to match with the system's pillar. For
example, the value of the "role" pillar could be used to pull values
from the ``lookup_dict`` dictionary.
The pillar value can be a list. The function will return the
``lookup_dict`` value for a first found item in the list matching
one of the ``lookup_dict`` keys.
:param merge: A dictionary to merge with the results of the pillar
selection from ``lookup_dict``. This allows another dictionary to
override the values in the ``lookup_dict``.
:param default: default lookup_dict's key used if the pillar does not exist
or if the pillar value has no match on lookup_dict. If unspecified
the value is "default".
:param base: A lookup_dict key to use for a base dictionary. The
pillar-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the pillar
selection dictionary and the merge dictionary. Default is unset.
CLI Example:
.. code-block:: bash
salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role
'''
return salt.utils.data.filter_by(lookup_dict=lookup_dict,
lookup=pillar,
traverse=__pillar__,
merge=merge,
default=default,
base=base)
|
saltstack/salt
|
salt/modules/pillar.py
|
ext
|
python
|
def ext(external, pillar=None):
'''
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single ext_pillar to add to the ext_pillar configuration. This must
be passed as a single section from the ext_pillar configuration (see
CLI examples below). For more complicated ``ext_pillar``
configurations, it can be helpful to use the Python shell to load YAML
configuration into a dictionary, and figure out
.. code-block:: python
>>> import salt.utils.yaml
>>> ext_pillar = salt.utils.yaml.safe_load("""
... ext_pillar:
... - git:
... - issue38440 https://github.com/terminalmage/git_pillar:
... - env: base
... """)
>>> ext_pillar
{'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]}
>>> ext_pillar['ext_pillar'][0]
{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}
In the above example, the value to pass would be
``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``.
Note that this would need to be quoted when passing on the CLI (as in
the CLI examples below).
pillar : None
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. These pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' pillar.ext '{libvirt: _}'
salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}"
salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}"
'''
if isinstance(external, six.string_types):
external = salt.utils.yaml.safe_load(external)
pillar_obj = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
ext=external,
pillar_override=pillar)
ret = pillar_obj.compile_pillar()
return ret
|
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single ext_pillar to add to the ext_pillar configuration. This must
be passed as a single section from the ext_pillar configuration (see
CLI examples below). For more complicated ``ext_pillar``
configurations, it can be helpful to use the Python shell to load YAML
configuration into a dictionary, and figure out
.. code-block:: python
>>> import salt.utils.yaml
>>> ext_pillar = salt.utils.yaml.safe_load("""
... ext_pillar:
... - git:
... - issue38440 https://github.com/terminalmage/git_pillar:
... - env: base
... """)
>>> ext_pillar
{'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]}
>>> ext_pillar['ext_pillar'][0]
{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}
In the above example, the value to pass would be
``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``.
Note that this would need to be quoted when passing on the CLI (as in
the CLI examples below).
pillar : None
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. These pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' pillar.ext '{libvirt: _}'
salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}"
salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pillar.py#L452-L516
|
[
"def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n",
"def get_pillar(opts, grains, minion_id, saltenv=None, ext=None, funcs=None,\n pillar_override=None, pillarenv=None, extra_minion_data=None):\n '''\n Return the correct pillar driver based on the file_client option\n '''\n file_client = opts['file_client']\n if opts.get('master_type') == 'disable' and file_client == 'remote':\n file_client = 'local'\n ptype = {\n 'remote': RemotePillar,\n 'local': Pillar\n }.get(file_client, Pillar)\n # If local pillar and we're caching, run through the cache system first\n log.debug('Determining pillar cache')\n if opts['pillar_cache']:\n log.info('Compiling pillar from cache')\n log.debug('get_pillar using pillar cache with ext: %s', ext)\n return PillarCache(opts, grains, minion_id, saltenv, ext=ext, functions=funcs,\n pillar_override=pillar_override, pillarenv=pillarenv)\n return ptype(opts, grains, minion_id, saltenv, ext, functions=funcs,\n pillar_override=pillar_override, pillarenv=pillarenv,\n extra_minion_data=extra_minion_data)\n",
"def compile_pillar(self, *args, **kwargs): # Will likely just be pillar_dirs\n '''\n Compile pillar and set it to the cache, if not found.\n\n :param args:\n :param kwargs:\n :return:\n '''\n log.debug('Scanning pillar cache for information about minion %s and pillarenv %s', self.minion_id, self.pillarenv)\n log.debug('Scanning cache for minion %s: %s', self.minion_id, self.cache[self.minion_id] or '*empty*')\n\n # Check the cache!\n if self.minion_id in self.cache: # Keyed by minion_id\n # TODO Compare grains, etc?\n if self.pillarenv in self.cache[self.minion_id]:\n # We have a cache hit! Send it back.\n log.debug('Pillar cache hit for minion %s and pillarenv %s', self.minion_id, self.pillarenv)\n pillar_data = self.cache[self.minion_id][self.pillarenv]\n else:\n # We found the minion but not the env. Store it.\n pillar_data = self.fetch_pillar()\n self.cache[self.minion_id][self.pillarenv] = pillar_data\n self.cache.store()\n log.debug('Pillar cache miss for pillarenv %s for minion %s', self.pillarenv, self.minion_id)\n else:\n # We haven't seen this minion yet in the cache. Store it.\n pillar_data = self.fetch_pillar()\n self.cache[self.minion_id] = {self.pillarenv: pillar_data}\n log.debug('Pillar cache has been added for minion %s', self.minion_id)\n log.debug('Current pillar cache: %s', self.cache[self.minion_id])\n\n # we dont want the pillar_override baked into the cached fetch_pillar from above\n if self.pillar_override:\n pillar_data = merge(\n pillar_data,\n self.pillar_override,\n self.opts.get('pillar_source_merging_strategy', 'smart'),\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n pillar_data.update(self.pillar_override)\n\n return pillar_data\n"
] |
# -*- coding: utf-8 -*-
'''
Extract the pillar data for this minion
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import collections
# Import third party libs
import copy
import os
import logging
from salt.ext import six
# Import salt libs
import salt.pillar
import salt.utils.crypt
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.functools
import salt.utils.odict
import salt.utils.yaml
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import CommandExecutionError
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def get(key,
default=KeyError,
merge=False,
merge_nested_lists=None,
delimiter=DEFAULT_TARGET_DELIM,
pillarenv=None,
saltenv=None):
'''
.. versionadded:: 0.14
Attempt to retrieve the named value from :ref:`in-memory pillar data
<pillar-in-memory>`. If the pillar key is not present in the in-memory
pillar, then the value specified in the ``default`` option (described
below) will be returned.
If the merge parameter is set to ``True``, the default will be recursively
merged into the returned pillar data.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict. This means that if a dict in pillar looks like this::
{'pkg': {'apache': 'httpd'}}
To retrieve the value associated with the ``apache`` key in the ``pkg``
dict this key can be passed as::
pkg:apache
key
The pillar key to get value from
default
The value specified by this option will be returned if the desired
pillar key does not exist.
If a default value is specified, then it will be an empty string,
unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in
which case an error will be raised.
merge : ``False``
If ``True``, the retrieved values will be merged into the passed
default. When the default and the retrieved value are both
dictionaries, the dictionaries will be recursively merged.
.. versionadded:: 2014.7.0
.. versionchanged:: 2016.3.7,2016.11.4,2017.7.0
If the default and the retrieved value are not of the same type,
then merging will be skipped and the retrieved value will be
returned. Earlier releases raised an error in these cases.
merge_nested_lists
If set to ``False``, lists nested within the retrieved pillar
dictionary will *overwrite* lists in ``default``. If set to ``True``,
nested lists will be *merged* into lists in ``default``. If unspecified
(the default), this option is inherited from the
:conf_minion:`pillar_merge_lists` minion config option.
.. note::
This option is ignored when ``merge`` is set to ``False``.
.. versionadded:: 2016.11.6
delimiter
Specify an alternate delimiter to use when traversing a nested dict.
This is useful for when the desired key contains a colon. See CLI
example below for usage.
.. versionadded:: 2014.7.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.0
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' pillar.get pkg:apache
salt '*' pillar.get abc::def|ghi delimiter='|'
'''
if not __opts__.get('pillar_raise_on_missing'):
if default is KeyError:
default = ''
opt_merge_lists = __opts__.get('pillar_merge_lists', False) if \
merge_nested_lists is None else merge_nested_lists
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
if merge:
if isinstance(default, dict):
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
{},
delimiter)
if isinstance(ret, collections.Mapping):
default = copy.deepcopy(default)
return salt.utils.dictupdate.update(
default,
ret,
merge_lists=opt_merge_lists)
else:
log.error(
'pillar.get: Default (%s) is a dict, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
elif isinstance(default, list):
ret = salt.utils.data.traverse_dict_and_list( # pylint: disable=redefined-variable-type
pillar_dict,
key,
[],
delimiter)
if isinstance(ret, list):
default = copy.deepcopy(default)
default.extend([x for x in ret if x not in default])
return default
else:
log.error(
'pillar.get: Default (%s) is a list, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
else:
log.error(
'pillar.get: Default (%s) is of type \'%s\', must be a dict '
'or list to merge. Merge will be skipped.',
default, type(default).__name__
)
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
default,
delimiter)
if ret is KeyError:
raise KeyError('Pillar key not found: {0}'.format(key))
return ret
def items(*args, **kwargs):
'''
Calls the master for a fresh pillar and generates the pillar data on the
fly
Contrast with :py:func:`raw` which returns the pillar data that is
currently loaded into the minion.
pillar
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. these pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
pillar_enc
If specified, the data passed in the ``pillar`` argument will be passed
through this renderer to decrypt it.
.. note::
This will decrypt on the minion side, so the specified renderer
must be set up on the minion for this to work. Alternatively,
pillar data can be decrypted master-side. For more information, see
the :ref:`Pillar Encryption <pillar-encryption>` documentation.
Pillar data that is decrypted master-side, is not decrypted until
the end of pillar compilation though, so minion-side decryption
will be necessary if the encrypted pillar data must be made
available in an decrypted state pillar/ext_pillar rendering.
.. versionadded:: 2017.7.0
pillarenv
Pass a specific pillar environment from which to compile pillar data.
If not specified, then the minion's :conf_minion:`pillarenv` option is
not used, and if that also is not specified then all configured pillar
environments will be merged into a single pillar dictionary and
returned.
.. versionadded:: 2016.11.2
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
CLI Example:
.. code-block:: bash
salt '*' pillar.items
'''
# Preserve backwards compatibility
if args:
return item(*args)
pillarenv = kwargs.get('pillarenv')
if pillarenv is None:
if __opts__.get('pillarenv_from_saltenv', False):
pillarenv = kwargs.get('saltenv') or __opts__['saltenv']
else:
pillarenv = __opts__['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_override and pillar_enc:
try:
pillar_override = salt.utils.crypt.decrypt(
pillar_override,
pillar_enc,
translate_newlines=True,
opts=__opts__,
valid_rend=__opts__['decrypt_pillar_renderers'])
except Exception as exc:
raise CommandExecutionError(
'Failed to decrypt pillar override: {0}'.format(exc)
)
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
pillar_override=pillar_override,
pillarenv=pillarenv)
return pillar.compile_pillar()
# Allow pillar.data to also be used to return pillar data
data = salt.utils.functools.alias_function(items, 'data')
def _obfuscate_inner(var):
'''
Recursive obfuscation of collection types.
Leaf or unknown Python types get replaced by the type name
Known collection types trigger recursion.
In the special case of mapping types, keys are not obfuscated
'''
if isinstance(var, (dict, salt.utils.odict.OrderedDict)):
return var.__class__((key, _obfuscate_inner(val))
for key, val in six.iteritems(var))
elif isinstance(var, (list, set, tuple)):
return type(var)(_obfuscate_inner(v) for v in var)
else:
return '<{0}>'.format(var.__class__.__name__)
def obfuscate(*args):
'''
.. versionadded:: 2015.8.0
Same as :py:func:`items`, but replace pillar values with a simple type indication.
This is useful to avoid displaying sensitive information on console or
flooding the console with long output, such as certificates.
For many debug or control purposes, the stakes lie more in dispatching than in
actual values.
In case the value is itself a collection type, obfuscation occurs within the value.
For mapping types, keys are not obfuscated.
Here are some examples:
* ``'secret password'`` becomes ``'<str>'``
* ``['secret', 1]`` becomes ``['<str>', '<int>']``
* ``{'login': 'somelogin', 'pwd': 'secret'}`` becomes
``{'login': '<str>', 'pwd': '<str>'}``
CLI Examples:
.. code-block:: bash
salt '*' pillar.obfuscate
'''
return _obfuscate_inner(items(*args))
# naming chosen for consistency with grains.ls, although it breaks the short
# identifier rule.
def ls(*args):
'''
.. versionadded:: 2015.8.0
Calls the master for a fresh pillar, generates the pillar data on the
fly (same as :py:func:`items`), but only shows the available main keys.
CLI Examples:
.. code-block:: bash
salt '*' pillar.ls
'''
return list(items(*args))
def item(*args, **kwargs):
'''
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
<salt.modules.pillar.get>` in that no default value can be
specified. :py:func:`pillar.get <salt.modules.pillar.get>` should
probably still be used in most cases to retrieve nested pillar
values, as it is a bit more flexible. One reason to use this
function instead of :py:func:`pillar.get <salt.modules.pillar.get>`
however is when it is desirable to retrieve the values of more than
one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can
only retrieve one key at a time.
.. versionadded:: 2015.8.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.6,2018.3.1
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.6,2018.3.1
CLI Examples:
.. code-block:: bash
salt '*' pillar.item foo
salt '*' pillar.item foo:bar
salt '*' pillar.item foo bar baz
'''
ret = {}
default = kwargs.get('default', '')
delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM)
pillarenv = kwargs.get('pillarenv', None)
saltenv = kwargs.get('saltenv', None)
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
try:
for arg in args:
ret[arg] = salt.utils.data.traverse_dict_and_list(
pillar_dict,
arg,
default,
delimiter)
except KeyError:
pass
return ret
def raw(key=None):
'''
Return the raw pillar data that is currently loaded into the minion.
Contrast with :py:func:`items` which calls the master to fetch the most
up-to-date Pillar.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw data.::
salt '*' pillar.raw key='roles'
'''
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
def keys(key, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2015.8.0
Attempt to retrieve a list of keys from the named value from the pillar.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict, similar to how pillar.get works.
delimiter
Specify an alternate delimiter to use when traversing a nested dict
CLI Example:
.. code-block:: bash
salt '*' pillar.keys web:sites
'''
ret = salt.utils.data.traverse_dict_and_list(
__pillar__, key, KeyError, delimiter)
if ret is KeyError:
raise KeyError("Pillar key not found: {0}".format(key))
if not isinstance(ret, dict):
raise ValueError("Pillar value in key {0} is not a dict".format(key))
return list(ret)
def file_exists(path, saltenv=None):
'''
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
'''
pillar_roots = __opts__.get('pillar_roots')
if not pillar_roots:
raise CommandExecutionError('No pillar_roots found. Are you running '
'this on the master?')
if saltenv:
if saltenv in pillar_roots:
pillar_roots = {saltenv: pillar_roots[saltenv]}
else:
return False
for env in pillar_roots:
for pillar_dir in pillar_roots[env]:
full_path = os.path.join(pillar_dir, path)
if __salt__['file.file_exists'](full_path):
return True
return False
# Provide a jinja function call compatible get aliased as fetch
fetch = get
def filter_by(lookup_dict,
pillar,
merge=None,
default='default',
base=None):
'''
.. versionadded:: 2017.7.0
Look up the given pillar in a given dictionary and return the result
:param lookup_dict: A dictionary, keyed by a pillar, containing a value or
values relevant to systems matching that pillar. For example, a key
could be a pillar for a role and the value could the name of a package
on that particular OS.
The dictionary key can be a globbing pattern. The function will return
the corresponding ``lookup_dict`` value where the pillar value matches
the pattern. For example:
.. code-block:: bash
# this will render 'got some salt' if ``role`` begins with 'salt'
salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role
:param pillar: The name of a pillar to match with the system's pillar. For
example, the value of the "role" pillar could be used to pull values
from the ``lookup_dict`` dictionary.
The pillar value can be a list. The function will return the
``lookup_dict`` value for a first found item in the list matching
one of the ``lookup_dict`` keys.
:param merge: A dictionary to merge with the results of the pillar
selection from ``lookup_dict``. This allows another dictionary to
override the values in the ``lookup_dict``.
:param default: default lookup_dict's key used if the pillar does not exist
or if the pillar value has no match on lookup_dict. If unspecified
the value is "default".
:param base: A lookup_dict key to use for a base dictionary. The
pillar-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the pillar
selection dictionary and the merge dictionary. Default is unset.
CLI Example:
.. code-block:: bash
salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role
'''
return salt.utils.data.filter_by(lookup_dict=lookup_dict,
lookup=pillar,
traverse=__pillar__,
merge=merge,
default=default,
base=base)
|
saltstack/salt
|
salt/modules/pillar.py
|
file_exists
|
python
|
def file_exists(path, saltenv=None):
'''
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
'''
pillar_roots = __opts__.get('pillar_roots')
if not pillar_roots:
raise CommandExecutionError('No pillar_roots found. Are you running '
'this on the master?')
if saltenv:
if saltenv in pillar_roots:
pillar_roots = {saltenv: pillar_roots[saltenv]}
else:
return False
for env in pillar_roots:
for pillar_dir in pillar_roots[env]:
full_path = os.path.join(pillar_dir, path)
if __salt__['file.file_exists'](full_path):
return True
return False
|
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pillar.py#L549-L594
| null |
# -*- coding: utf-8 -*-
'''
Extract the pillar data for this minion
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import collections
# Import third party libs
import copy
import os
import logging
from salt.ext import six
# Import salt libs
import salt.pillar
import salt.utils.crypt
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.functools
import salt.utils.odict
import salt.utils.yaml
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import CommandExecutionError
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def get(key,
default=KeyError,
merge=False,
merge_nested_lists=None,
delimiter=DEFAULT_TARGET_DELIM,
pillarenv=None,
saltenv=None):
'''
.. versionadded:: 0.14
Attempt to retrieve the named value from :ref:`in-memory pillar data
<pillar-in-memory>`. If the pillar key is not present in the in-memory
pillar, then the value specified in the ``default`` option (described
below) will be returned.
If the merge parameter is set to ``True``, the default will be recursively
merged into the returned pillar data.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict. This means that if a dict in pillar looks like this::
{'pkg': {'apache': 'httpd'}}
To retrieve the value associated with the ``apache`` key in the ``pkg``
dict this key can be passed as::
pkg:apache
key
The pillar key to get value from
default
The value specified by this option will be returned if the desired
pillar key does not exist.
If a default value is specified, then it will be an empty string,
unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in
which case an error will be raised.
merge : ``False``
If ``True``, the retrieved values will be merged into the passed
default. When the default and the retrieved value are both
dictionaries, the dictionaries will be recursively merged.
.. versionadded:: 2014.7.0
.. versionchanged:: 2016.3.7,2016.11.4,2017.7.0
If the default and the retrieved value are not of the same type,
then merging will be skipped and the retrieved value will be
returned. Earlier releases raised an error in these cases.
merge_nested_lists
If set to ``False``, lists nested within the retrieved pillar
dictionary will *overwrite* lists in ``default``. If set to ``True``,
nested lists will be *merged* into lists in ``default``. If unspecified
(the default), this option is inherited from the
:conf_minion:`pillar_merge_lists` minion config option.
.. note::
This option is ignored when ``merge`` is set to ``False``.
.. versionadded:: 2016.11.6
delimiter
Specify an alternate delimiter to use when traversing a nested dict.
This is useful for when the desired key contains a colon. See CLI
example below for usage.
.. versionadded:: 2014.7.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.0
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' pillar.get pkg:apache
salt '*' pillar.get abc::def|ghi delimiter='|'
'''
if not __opts__.get('pillar_raise_on_missing'):
if default is KeyError:
default = ''
opt_merge_lists = __opts__.get('pillar_merge_lists', False) if \
merge_nested_lists is None else merge_nested_lists
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
if merge:
if isinstance(default, dict):
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
{},
delimiter)
if isinstance(ret, collections.Mapping):
default = copy.deepcopy(default)
return salt.utils.dictupdate.update(
default,
ret,
merge_lists=opt_merge_lists)
else:
log.error(
'pillar.get: Default (%s) is a dict, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
elif isinstance(default, list):
ret = salt.utils.data.traverse_dict_and_list( # pylint: disable=redefined-variable-type
pillar_dict,
key,
[],
delimiter)
if isinstance(ret, list):
default = copy.deepcopy(default)
default.extend([x for x in ret if x not in default])
return default
else:
log.error(
'pillar.get: Default (%s) is a list, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
else:
log.error(
'pillar.get: Default (%s) is of type \'%s\', must be a dict '
'or list to merge. Merge will be skipped.',
default, type(default).__name__
)
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
default,
delimiter)
if ret is KeyError:
raise KeyError('Pillar key not found: {0}'.format(key))
return ret
def items(*args, **kwargs):
'''
Calls the master for a fresh pillar and generates the pillar data on the
fly
Contrast with :py:func:`raw` which returns the pillar data that is
currently loaded into the minion.
pillar
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. these pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
pillar_enc
If specified, the data passed in the ``pillar`` argument will be passed
through this renderer to decrypt it.
.. note::
This will decrypt on the minion side, so the specified renderer
must be set up on the minion for this to work. Alternatively,
pillar data can be decrypted master-side. For more information, see
the :ref:`Pillar Encryption <pillar-encryption>` documentation.
Pillar data that is decrypted master-side, is not decrypted until
the end of pillar compilation though, so minion-side decryption
will be necessary if the encrypted pillar data must be made
available in an decrypted state pillar/ext_pillar rendering.
.. versionadded:: 2017.7.0
pillarenv
Pass a specific pillar environment from which to compile pillar data.
If not specified, then the minion's :conf_minion:`pillarenv` option is
not used, and if that also is not specified then all configured pillar
environments will be merged into a single pillar dictionary and
returned.
.. versionadded:: 2016.11.2
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
CLI Example:
.. code-block:: bash
salt '*' pillar.items
'''
# Preserve backwards compatibility
if args:
return item(*args)
pillarenv = kwargs.get('pillarenv')
if pillarenv is None:
if __opts__.get('pillarenv_from_saltenv', False):
pillarenv = kwargs.get('saltenv') or __opts__['saltenv']
else:
pillarenv = __opts__['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_override and pillar_enc:
try:
pillar_override = salt.utils.crypt.decrypt(
pillar_override,
pillar_enc,
translate_newlines=True,
opts=__opts__,
valid_rend=__opts__['decrypt_pillar_renderers'])
except Exception as exc:
raise CommandExecutionError(
'Failed to decrypt pillar override: {0}'.format(exc)
)
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
pillar_override=pillar_override,
pillarenv=pillarenv)
return pillar.compile_pillar()
# Allow pillar.data to also be used to return pillar data
data = salt.utils.functools.alias_function(items, 'data')
def _obfuscate_inner(var):
'''
Recursive obfuscation of collection types.
Leaf or unknown Python types get replaced by the type name
Known collection types trigger recursion.
In the special case of mapping types, keys are not obfuscated
'''
if isinstance(var, (dict, salt.utils.odict.OrderedDict)):
return var.__class__((key, _obfuscate_inner(val))
for key, val in six.iteritems(var))
elif isinstance(var, (list, set, tuple)):
return type(var)(_obfuscate_inner(v) for v in var)
else:
return '<{0}>'.format(var.__class__.__name__)
def obfuscate(*args):
'''
.. versionadded:: 2015.8.0
Same as :py:func:`items`, but replace pillar values with a simple type indication.
This is useful to avoid displaying sensitive information on console or
flooding the console with long output, such as certificates.
For many debug or control purposes, the stakes lie more in dispatching than in
actual values.
In case the value is itself a collection type, obfuscation occurs within the value.
For mapping types, keys are not obfuscated.
Here are some examples:
* ``'secret password'`` becomes ``'<str>'``
* ``['secret', 1]`` becomes ``['<str>', '<int>']``
* ``{'login': 'somelogin', 'pwd': 'secret'}`` becomes
``{'login': '<str>', 'pwd': '<str>'}``
CLI Examples:
.. code-block:: bash
salt '*' pillar.obfuscate
'''
return _obfuscate_inner(items(*args))
# naming chosen for consistency with grains.ls, although it breaks the short
# identifier rule.
def ls(*args):
'''
.. versionadded:: 2015.8.0
Calls the master for a fresh pillar, generates the pillar data on the
fly (same as :py:func:`items`), but only shows the available main keys.
CLI Examples:
.. code-block:: bash
salt '*' pillar.ls
'''
return list(items(*args))
def item(*args, **kwargs):
'''
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
<salt.modules.pillar.get>` in that no default value can be
specified. :py:func:`pillar.get <salt.modules.pillar.get>` should
probably still be used in most cases to retrieve nested pillar
values, as it is a bit more flexible. One reason to use this
function instead of :py:func:`pillar.get <salt.modules.pillar.get>`
however is when it is desirable to retrieve the values of more than
one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can
only retrieve one key at a time.
.. versionadded:: 2015.8.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.6,2018.3.1
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.6,2018.3.1
CLI Examples:
.. code-block:: bash
salt '*' pillar.item foo
salt '*' pillar.item foo:bar
salt '*' pillar.item foo bar baz
'''
ret = {}
default = kwargs.get('default', '')
delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM)
pillarenv = kwargs.get('pillarenv', None)
saltenv = kwargs.get('saltenv', None)
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
try:
for arg in args:
ret[arg] = salt.utils.data.traverse_dict_and_list(
pillar_dict,
arg,
default,
delimiter)
except KeyError:
pass
return ret
def raw(key=None):
'''
Return the raw pillar data that is currently loaded into the minion.
Contrast with :py:func:`items` which calls the master to fetch the most
up-to-date Pillar.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw data.::
salt '*' pillar.raw key='roles'
'''
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
def ext(external, pillar=None):
'''
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single ext_pillar to add to the ext_pillar configuration. This must
be passed as a single section from the ext_pillar configuration (see
CLI examples below). For more complicated ``ext_pillar``
configurations, it can be helpful to use the Python shell to load YAML
configuration into a dictionary, and figure out
.. code-block:: python
>>> import salt.utils.yaml
>>> ext_pillar = salt.utils.yaml.safe_load("""
... ext_pillar:
... - git:
... - issue38440 https://github.com/terminalmage/git_pillar:
... - env: base
... """)
>>> ext_pillar
{'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]}
>>> ext_pillar['ext_pillar'][0]
{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}
In the above example, the value to pass would be
``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``.
Note that this would need to be quoted when passing on the CLI (as in
the CLI examples below).
pillar : None
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. These pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' pillar.ext '{libvirt: _}'
salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}"
salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}"
'''
if isinstance(external, six.string_types):
external = salt.utils.yaml.safe_load(external)
pillar_obj = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
ext=external,
pillar_override=pillar)
ret = pillar_obj.compile_pillar()
return ret
def keys(key, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2015.8.0
Attempt to retrieve a list of keys from the named value from the pillar.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict, similar to how pillar.get works.
delimiter
Specify an alternate delimiter to use when traversing a nested dict
CLI Example:
.. code-block:: bash
salt '*' pillar.keys web:sites
'''
ret = salt.utils.data.traverse_dict_and_list(
__pillar__, key, KeyError, delimiter)
if ret is KeyError:
raise KeyError("Pillar key not found: {0}".format(key))
if not isinstance(ret, dict):
raise ValueError("Pillar value in key {0} is not a dict".format(key))
return list(ret)
# Provide a jinja function call compatible get aliased as fetch
fetch = get
def filter_by(lookup_dict,
pillar,
merge=None,
default='default',
base=None):
'''
.. versionadded:: 2017.7.0
Look up the given pillar in a given dictionary and return the result
:param lookup_dict: A dictionary, keyed by a pillar, containing a value or
values relevant to systems matching that pillar. For example, a key
could be a pillar for a role and the value could the name of a package
on that particular OS.
The dictionary key can be a globbing pattern. The function will return
the corresponding ``lookup_dict`` value where the pillar value matches
the pattern. For example:
.. code-block:: bash
# this will render 'got some salt' if ``role`` begins with 'salt'
salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role
:param pillar: The name of a pillar to match with the system's pillar. For
example, the value of the "role" pillar could be used to pull values
from the ``lookup_dict`` dictionary.
The pillar value can be a list. The function will return the
``lookup_dict`` value for a first found item in the list matching
one of the ``lookup_dict`` keys.
:param merge: A dictionary to merge with the results of the pillar
selection from ``lookup_dict``. This allows another dictionary to
override the values in the ``lookup_dict``.
:param default: default lookup_dict's key used if the pillar does not exist
or if the pillar value has no match on lookup_dict. If unspecified
the value is "default".
:param base: A lookup_dict key to use for a base dictionary. The
pillar-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the pillar
selection dictionary and the merge dictionary. Default is unset.
CLI Example:
.. code-block:: bash
salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role
'''
return salt.utils.data.filter_by(lookup_dict=lookup_dict,
lookup=pillar,
traverse=__pillar__,
merge=merge,
default=default,
base=base)
|
saltstack/salt
|
salt/modules/pillar.py
|
filter_by
|
python
|
def filter_by(lookup_dict,
pillar,
merge=None,
default='default',
base=None):
'''
.. versionadded:: 2017.7.0
Look up the given pillar in a given dictionary and return the result
:param lookup_dict: A dictionary, keyed by a pillar, containing a value or
values relevant to systems matching that pillar. For example, a key
could be a pillar for a role and the value could the name of a package
on that particular OS.
The dictionary key can be a globbing pattern. The function will return
the corresponding ``lookup_dict`` value where the pillar value matches
the pattern. For example:
.. code-block:: bash
# this will render 'got some salt' if ``role`` begins with 'salt'
salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role
:param pillar: The name of a pillar to match with the system's pillar. For
example, the value of the "role" pillar could be used to pull values
from the ``lookup_dict`` dictionary.
The pillar value can be a list. The function will return the
``lookup_dict`` value for a first found item in the list matching
one of the ``lookup_dict`` keys.
:param merge: A dictionary to merge with the results of the pillar
selection from ``lookup_dict``. This allows another dictionary to
override the values in the ``lookup_dict``.
:param default: default lookup_dict's key used if the pillar does not exist
or if the pillar value has no match on lookup_dict. If unspecified
the value is "default".
:param base: A lookup_dict key to use for a base dictionary. The
pillar-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the pillar
selection dictionary and the merge dictionary. Default is unset.
CLI Example:
.. code-block:: bash
salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role
'''
return salt.utils.data.filter_by(lookup_dict=lookup_dict,
lookup=pillar,
traverse=__pillar__,
merge=merge,
default=default,
base=base)
|
.. versionadded:: 2017.7.0
Look up the given pillar in a given dictionary and return the result
:param lookup_dict: A dictionary, keyed by a pillar, containing a value or
values relevant to systems matching that pillar. For example, a key
could be a pillar for a role and the value could the name of a package
on that particular OS.
The dictionary key can be a globbing pattern. The function will return
the corresponding ``lookup_dict`` value where the pillar value matches
the pattern. For example:
.. code-block:: bash
# this will render 'got some salt' if ``role`` begins with 'salt'
salt '*' pillar.filter_by '{salt*: got some salt, default: salt is not here}' role
:param pillar: The name of a pillar to match with the system's pillar. For
example, the value of the "role" pillar could be used to pull values
from the ``lookup_dict`` dictionary.
The pillar value can be a list. The function will return the
``lookup_dict`` value for a first found item in the list matching
one of the ``lookup_dict`` keys.
:param merge: A dictionary to merge with the results of the pillar
selection from ``lookup_dict``. This allows another dictionary to
override the values in the ``lookup_dict``.
:param default: default lookup_dict's key used if the pillar does not exist
or if the pillar value has no match on lookup_dict. If unspecified
the value is "default".
:param base: A lookup_dict key to use for a base dictionary. The
pillar-selected ``lookup_dict`` is merged over this and then finally
the ``merge`` dictionary is merged. This allows common values for
each case to be collected in the base and overridden by the pillar
selection dictionary and the merge dictionary. Default is unset.
CLI Example:
.. code-block:: bash
salt '*' pillar.filter_by '{web: Serve it up, db: I query, default: x_x}' role
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pillar.py#L601-L658
|
[
"def filter_by(lookup_dict,\n lookup,\n traverse,\n merge=None,\n default='default',\n base=None):\n '''\n Common code to filter data structures like grains and pillar\n '''\n ret = None\n # Default value would be an empty list if lookup not found\n val = traverse_dict_and_list(traverse, lookup, [])\n\n # Iterate over the list of values to match against patterns in the\n # lookup_dict keys\n for each in val if isinstance(val, list) else [val]:\n for key in lookup_dict:\n test_key = key if isinstance(key, six.string_types) \\\n else six.text_type(key)\n test_each = each if isinstance(each, six.string_types) \\\n else six.text_type(each)\n if fnmatch.fnmatchcase(test_each, test_key):\n ret = lookup_dict[key]\n break\n if ret is not None:\n break\n\n if ret is None:\n ret = lookup_dict.get(default, None)\n\n if base and base in lookup_dict:\n base_values = lookup_dict[base]\n if ret is None:\n ret = base_values\n\n elif isinstance(base_values, Mapping):\n if not isinstance(ret, Mapping):\n raise SaltException(\n 'filter_by default and look-up values must both be '\n 'dictionaries.')\n ret = salt.utils.dictupdate.update(copy.deepcopy(base_values), ret)\n\n if merge:\n if not isinstance(merge, Mapping):\n raise SaltException(\n 'filter_by merge argument must be a dictionary.')\n\n if ret is None:\n ret = merge\n else:\n salt.utils.dictupdate.update(ret, copy.deepcopy(merge))\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Extract the pillar data for this minion
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import collections
# Import third party libs
import copy
import os
import logging
from salt.ext import six
# Import salt libs
import salt.pillar
import salt.utils.crypt
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.functools
import salt.utils.odict
import salt.utils.yaml
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import CommandExecutionError
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def get(key,
default=KeyError,
merge=False,
merge_nested_lists=None,
delimiter=DEFAULT_TARGET_DELIM,
pillarenv=None,
saltenv=None):
'''
.. versionadded:: 0.14
Attempt to retrieve the named value from :ref:`in-memory pillar data
<pillar-in-memory>`. If the pillar key is not present in the in-memory
pillar, then the value specified in the ``default`` option (described
below) will be returned.
If the merge parameter is set to ``True``, the default will be recursively
merged into the returned pillar data.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict. This means that if a dict in pillar looks like this::
{'pkg': {'apache': 'httpd'}}
To retrieve the value associated with the ``apache`` key in the ``pkg``
dict this key can be passed as::
pkg:apache
key
The pillar key to get value from
default
The value specified by this option will be returned if the desired
pillar key does not exist.
If a default value is specified, then it will be an empty string,
unless :conf_minion:`pillar_raise_on_missing` is set to ``True``, in
which case an error will be raised.
merge : ``False``
If ``True``, the retrieved values will be merged into the passed
default. When the default and the retrieved value are both
dictionaries, the dictionaries will be recursively merged.
.. versionadded:: 2014.7.0
.. versionchanged:: 2016.3.7,2016.11.4,2017.7.0
If the default and the retrieved value are not of the same type,
then merging will be skipped and the retrieved value will be
returned. Earlier releases raised an error in these cases.
merge_nested_lists
If set to ``False``, lists nested within the retrieved pillar
dictionary will *overwrite* lists in ``default``. If set to ``True``,
nested lists will be *merged* into lists in ``default``. If unspecified
(the default), this option is inherited from the
:conf_minion:`pillar_merge_lists` minion config option.
.. note::
This option is ignored when ``merge`` is set to ``False``.
.. versionadded:: 2016.11.6
delimiter
Specify an alternate delimiter to use when traversing a nested dict.
This is useful for when the desired key contains a colon. See CLI
example below for usage.
.. versionadded:: 2014.7.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.0
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' pillar.get pkg:apache
salt '*' pillar.get abc::def|ghi delimiter='|'
'''
if not __opts__.get('pillar_raise_on_missing'):
if default is KeyError:
default = ''
opt_merge_lists = __opts__.get('pillar_merge_lists', False) if \
merge_nested_lists is None else merge_nested_lists
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
if merge:
if isinstance(default, dict):
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
{},
delimiter)
if isinstance(ret, collections.Mapping):
default = copy.deepcopy(default)
return salt.utils.dictupdate.update(
default,
ret,
merge_lists=opt_merge_lists)
else:
log.error(
'pillar.get: Default (%s) is a dict, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
elif isinstance(default, list):
ret = salt.utils.data.traverse_dict_and_list( # pylint: disable=redefined-variable-type
pillar_dict,
key,
[],
delimiter)
if isinstance(ret, list):
default = copy.deepcopy(default)
default.extend([x for x in ret if x not in default])
return default
else:
log.error(
'pillar.get: Default (%s) is a list, but the returned '
'pillar value (%s) is of type \'%s\'. Merge will be '
'skipped.', default, ret, type(ret).__name__
)
else:
log.error(
'pillar.get: Default (%s) is of type \'%s\', must be a dict '
'or list to merge. Merge will be skipped.',
default, type(default).__name__
)
ret = salt.utils.data.traverse_dict_and_list(
pillar_dict,
key,
default,
delimiter)
if ret is KeyError:
raise KeyError('Pillar key not found: {0}'.format(key))
return ret
def items(*args, **kwargs):
'''
Calls the master for a fresh pillar and generates the pillar data on the
fly
Contrast with :py:func:`raw` which returns the pillar data that is
currently loaded into the minion.
pillar
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. these pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
pillar_enc
If specified, the data passed in the ``pillar`` argument will be passed
through this renderer to decrypt it.
.. note::
This will decrypt on the minion side, so the specified renderer
must be set up on the minion for this to work. Alternatively,
pillar data can be decrypted master-side. For more information, see
the :ref:`Pillar Encryption <pillar-encryption>` documentation.
Pillar data that is decrypted master-side, is not decrypted until
the end of pillar compilation though, so minion-side decryption
will be necessary if the encrypted pillar data must be made
available in an decrypted state pillar/ext_pillar rendering.
.. versionadded:: 2017.7.0
pillarenv
Pass a specific pillar environment from which to compile pillar data.
If not specified, then the minion's :conf_minion:`pillarenv` option is
not used, and if that also is not specified then all configured pillar
environments will be merged into a single pillar dictionary and
returned.
.. versionadded:: 2016.11.2
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
CLI Example:
.. code-block:: bash
salt '*' pillar.items
'''
# Preserve backwards compatibility
if args:
return item(*args)
pillarenv = kwargs.get('pillarenv')
if pillarenv is None:
if __opts__.get('pillarenv_from_saltenv', False):
pillarenv = kwargs.get('saltenv') or __opts__['saltenv']
else:
pillarenv = __opts__['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_override and pillar_enc:
try:
pillar_override = salt.utils.crypt.decrypt(
pillar_override,
pillar_enc,
translate_newlines=True,
opts=__opts__,
valid_rend=__opts__['decrypt_pillar_renderers'])
except Exception as exc:
raise CommandExecutionError(
'Failed to decrypt pillar override: {0}'.format(exc)
)
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
pillar_override=pillar_override,
pillarenv=pillarenv)
return pillar.compile_pillar()
# Allow pillar.data to also be used to return pillar data
data = salt.utils.functools.alias_function(items, 'data')
def _obfuscate_inner(var):
'''
Recursive obfuscation of collection types.
Leaf or unknown Python types get replaced by the type name
Known collection types trigger recursion.
In the special case of mapping types, keys are not obfuscated
'''
if isinstance(var, (dict, salt.utils.odict.OrderedDict)):
return var.__class__((key, _obfuscate_inner(val))
for key, val in six.iteritems(var))
elif isinstance(var, (list, set, tuple)):
return type(var)(_obfuscate_inner(v) for v in var)
else:
return '<{0}>'.format(var.__class__.__name__)
def obfuscate(*args):
'''
.. versionadded:: 2015.8.0
Same as :py:func:`items`, but replace pillar values with a simple type indication.
This is useful to avoid displaying sensitive information on console or
flooding the console with long output, such as certificates.
For many debug or control purposes, the stakes lie more in dispatching than in
actual values.
In case the value is itself a collection type, obfuscation occurs within the value.
For mapping types, keys are not obfuscated.
Here are some examples:
* ``'secret password'`` becomes ``'<str>'``
* ``['secret', 1]`` becomes ``['<str>', '<int>']``
* ``{'login': 'somelogin', 'pwd': 'secret'}`` becomes
``{'login': '<str>', 'pwd': '<str>'}``
CLI Examples:
.. code-block:: bash
salt '*' pillar.obfuscate
'''
return _obfuscate_inner(items(*args))
# naming chosen for consistency with grains.ls, although it breaks the short
# identifier rule.
def ls(*args):
'''
.. versionadded:: 2015.8.0
Calls the master for a fresh pillar, generates the pillar data on the
fly (same as :py:func:`items`), but only shows the available main keys.
CLI Examples:
.. code-block:: bash
salt '*' pillar.ls
'''
return list(items(*args))
def item(*args, **kwargs):
'''
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
<salt.modules.pillar.get>` in that no default value can be
specified. :py:func:`pillar.get <salt.modules.pillar.get>` should
probably still be used in most cases to retrieve nested pillar
values, as it is a bit more flexible. One reason to use this
function instead of :py:func:`pillar.get <salt.modules.pillar.get>`
however is when it is desirable to retrieve the values of more than
one key, since :py:func:`pillar.get <salt.modules.pillar.get>` can
only retrieve one key at a time.
.. versionadded:: 2015.8.0
pillarenv
If specified, this function will query the master to generate fresh
pillar data on the fly, specifically from the requested pillar
environment. Note that this can produce different pillar data than
executing this function without an environment, as its normal behavior
is just to return a value from minion's pillar data in memory (which
can be sourced from more than one pillar environment).
Using this argument will not affect the pillar data in memory. It will
however be slightly slower and use more resources on the master due to
the need for the master to generate and send the minion fresh pillar
data. This tradeoff in performance however allows for the use case
where pillar data is desired only from a single environment.
.. versionadded:: 2017.7.6,2018.3.1
saltenv
Included only for compatibility with
:conf_minion:`pillarenv_from_saltenv`, and is otherwise ignored.
.. versionadded:: 2017.7.6,2018.3.1
CLI Examples:
.. code-block:: bash
salt '*' pillar.item foo
salt '*' pillar.item foo:bar
salt '*' pillar.item foo bar baz
'''
ret = {}
default = kwargs.get('default', '')
delimiter = kwargs.get('delimiter', DEFAULT_TARGET_DELIM)
pillarenv = kwargs.get('pillarenv', None)
saltenv = kwargs.get('saltenv', None)
pillar_dict = __pillar__ \
if all(x is None for x in (saltenv, pillarenv)) \
else items(saltenv=saltenv, pillarenv=pillarenv)
try:
for arg in args:
ret[arg] = salt.utils.data.traverse_dict_and_list(
pillar_dict,
arg,
default,
delimiter)
except KeyError:
pass
return ret
def raw(key=None):
'''
Return the raw pillar data that is currently loaded into the minion.
Contrast with :py:func:`items` which calls the master to fetch the most
up-to-date Pillar.
CLI Example:
.. code-block:: bash
salt '*' pillar.raw
With the optional key argument, you can select a subtree of the
pillar raw data.::
salt '*' pillar.raw key='roles'
'''
if key:
ret = __pillar__.get(key, {})
else:
ret = __pillar__
return ret
def ext(external, pillar=None):
'''
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single ext_pillar to add to the ext_pillar configuration. This must
be passed as a single section from the ext_pillar configuration (see
CLI examples below). For more complicated ``ext_pillar``
configurations, it can be helpful to use the Python shell to load YAML
configuration into a dictionary, and figure out
.. code-block:: python
>>> import salt.utils.yaml
>>> ext_pillar = salt.utils.yaml.safe_load("""
... ext_pillar:
... - git:
... - issue38440 https://github.com/terminalmage/git_pillar:
... - env: base
... """)
>>> ext_pillar
{'ext_pillar': [{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}]}
>>> ext_pillar['ext_pillar'][0]
{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}
In the above example, the value to pass would be
``{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}``.
Note that this would need to be quoted when passing on the CLI (as in
the CLI examples below).
pillar : None
If specified, allows for a dictionary of pillar data to be made
available to pillar and ext_pillar rendering. These pillar variables
will also override any variables of the same name in pillar or
ext_pillar.
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' pillar.ext '{libvirt: _}'
salt '*' pillar.ext "{'git': ['master https://github.com/myuser/myrepo']}"
salt '*' pillar.ext "{'git': [{'mybranch https://github.com/myuser/myrepo': [{'env': 'base'}]}]}"
'''
if isinstance(external, six.string_types):
external = salt.utils.yaml.safe_load(external)
pillar_obj = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
ext=external,
pillar_override=pillar)
ret = pillar_obj.compile_pillar()
return ret
def keys(key, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2015.8.0
Attempt to retrieve a list of keys from the named value from the pillar.
The value can also represent a value in a nested dict using a ":" delimiter
for the dict, similar to how pillar.get works.
delimiter
Specify an alternate delimiter to use when traversing a nested dict
CLI Example:
.. code-block:: bash
salt '*' pillar.keys web:sites
'''
ret = salt.utils.data.traverse_dict_and_list(
__pillar__, key, KeyError, delimiter)
if ret is KeyError:
raise KeyError("Pillar key not found: {0}".format(key))
if not isinstance(ret, dict):
raise ValueError("Pillar value in key {0} is not a dict".format(key))
return list(ret)
def file_exists(path, saltenv=None):
'''
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
'''
pillar_roots = __opts__.get('pillar_roots')
if not pillar_roots:
raise CommandExecutionError('No pillar_roots found. Are you running '
'this on the master?')
if saltenv:
if saltenv in pillar_roots:
pillar_roots = {saltenv: pillar_roots[saltenv]}
else:
return False
for env in pillar_roots:
for pillar_dir in pillar_roots[env]:
full_path = os.path.join(pillar_dir, path)
if __salt__['file.file_exists'](full_path):
return True
return False
# Provide a jinja function call compatible get aliased as fetch
fetch = get
|
saltstack/salt
|
salt/modules/purefa.py
|
_get_system
|
python
|
def _get_system():
'''
Get Pure Storage FlashArray configuration
1) From the minion config
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
'''
agent = {'base': USER_AGENT_BASE,
'class': __name__,
'version': VERSION,
'platform': platform.platform()
}
user_agent = '{base} {class}/{version} ({platform})'.format(**agent)
try:
array = __opts__['pure_tags']['fa'].get('san_ip')
api = __opts__['pure_tags']['fa'].get('api_token')
if array and api:
system = purestorage.FlashArray(array, api_token=api, user_agent=user_agent)
except (KeyError, NameError, TypeError):
try:
san_ip = os.environ.get('PUREFA_IP')
api_token = os.environ.get('PUREFA_API')
system = purestorage.FlashArray(san_ip,
api_token=api_token,
user_agent=user_agent)
except (ValueError, KeyError, NameError):
try:
system = purestorage.FlashArray(__pillar__['PUREFA_IP'],
api_token=__pillar__['PUREFA_API'],
user_agent=user_agent)
except (KeyError, NameError):
raise CommandExecutionError('No Pure Storage FlashArray credentials found.')
try:
system.get()
except Exception:
raise CommandExecutionError('Pure Storage FlashArray authentication failed.')
return system
|
Get Pure Storage FlashArray configuration
1) From the minion config
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/purefa.py#L94-L139
| null |
# -*- coding: utf-8 -*-
##
# Copyright 2017 Pure Storage Inc
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Management of Pure Storage FlashArray
Installation Prerequisites
--------------------------
- You will need the ``purestorage`` python package in your python installation
path that is running salt.
.. code-block:: bash
pip install purestorage
- Configure Pure Storage FlashArray authentication. Use one of the following
three methods.
1) From the minion config
.. code-block:: yaml
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
:maintainer: Simon Dodsley (simon@purestorage.com)
:maturity: new
:requires: purestorage
:platform: all
.. versionadded:: 2018.3.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import platform
from datetime import datetime
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Import 3rd party modules
try:
import purestorage
HAS_PURESTORAGE = True
except ImportError:
HAS_PURESTORAGE = False
__docformat__ = 'restructuredtext en'
VERSION = '1.0.0'
USER_AGENT_BASE = 'Salt'
__virtualname__ = 'purefa'
# Default symbols to use for passwords. Avoids visually confusing characters.
# ~6 bits per symbol
DEFAULT_PASSWORD_SYMBOLS = ('23456789', # Removed: 0,1
'ABCDEFGHJKLMNPQRSTUVWXYZ', # Removed: I, O
'abcdefghijkmnopqrstuvwxyz') # Removed: l
def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURESTORAGE:
return __virtualname__
return (False, 'purefa execution module not loaded: purestorage python library not available.')
def _get_volume(name, array):
'''Private function to check volume'''
try:
return array.get_volume(name)
except purestorage.PureError:
return None
def _get_snapshot(name, suffix, array):
'''Private function to check snapshot'''
snapshot = name + '.' + suffix
try:
for snap in array.get_volume(name, snap=True):
if snap['name'] == snapshot:
return snapshot
except purestorage.PureError:
return None
def _get_deleted_volume(name, array):
'''Private function to check deleted volume'''
try:
return array.get_volume(name, pending='true')
except purestorage.PureError:
return None
def _get_pgroup(name, array):
'''Private function to check protection group'''
pgroup = None
for temp in array.list_pgroups():
if temp['name'] == name:
pgroup = temp
break
return pgroup
def _get_deleted_pgroup(name, array):
'''Private function to check deleted protection group'''
try:
return array.get_pgroup(name, pending='true')
except purestorage.PureError:
return None
def _get_hgroup(name, array):
'''Private function to check hostgroup'''
hostgroup = None
for temp in array.list_hgroups():
if temp['name'] == name:
hostgroup = temp
break
return hostgroup
def _get_host(name, array):
'''Private function to check host'''
host = None
for temp in array.list_hosts():
if temp['name'] == name:
host = temp
break
return host
def snap_create(name, suffix=None):
'''
Create a volume snapshot on a Pure Storage FlashArray.
Will return False is volume selected to snap does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume to snapshot
suffix : string
if specificed forces snapshot name suffix. If not specified defaults to timestamp.
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_create foo
salt '*' purefa.snap_create foo suffix=bar
'''
array = _get_system()
if suffix is None:
suffix = 'snap-' + six.text_type((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds())
suffix = suffix.replace('.', '')
if _get_volume(name, array) is not None:
try:
array.create_snapshot(name, suffix=suffix)
return True
except purestorage.PureError:
return False
else:
return False
def snap_delete(name, suffix=None, eradicate=False):
'''
Delete a volume snapshot on a Pure Storage FlashArray.
Will return False if selected snapshot does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
eradicate : boolean
Eradicate snapshot after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_delete foo suffix=snap eradicate=True
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
try:
snapname = name + '.' + suffix
array.destroy_volume(snapname)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def snap_eradicate(name, suffix=None):
'''
Eradicate a deleted volume snapshot on a Pure Storage FlashArray.
Will return False if snapshot is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_eradicate foo suffix=snap
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
snapname = name + '.' + suffix
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return False
def volume_create(name, size=None):
'''
Create a volume on a Pure Storage FlashArray.
Will return False if volume already exists.
.. versionadded:: 2018.3.0
name : string
name of volume (truncated to 63 characters)
size : string
if specificed capacity of volume. If not specified default to 1G.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_create foo
salt '*' purefa.volume_create foo size=10T
'''
if len(name) > 63:
name = name[0:63]
array = _get_system()
if _get_volume(name, array) is None:
if size is None:
size = '1G'
try:
array.create_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
def volume_delete(name, eradicate=False):
'''
Delete a volume on a Pure Storage FlashArray.
Will return False if volume doesn't exist is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
eradicate : boolean
Eradicate volume after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_delete foo eradicate=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
try:
array.destroy_volume(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def volume_eradicate(name):
'''
Eradicate a deleted volume on a Pure Storage FlashArray.
Will return False is volume is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_eradicate foo
'''
array = _get_system()
if _get_deleted_volume(name, array) is not None:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_extend(name, size):
'''
Extend an existing volume on a Pure Storage FlashArray.
Will return False if new size is less than or equal to existing size.
.. versionadded:: 2018.3.0
name : string
name of volume
size : string
New capacity of volume.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_extend foo 10T
'''
array = _get_system()
vol = _get_volume(name, array)
if vol is not None:
if __utils__['stringutils.human_to_bytes'](size) > vol['size']:
try:
array.extend_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def snap_volume_create(name, target, overwrite=False):
'''
Create R/W volume from snapshot on a Pure Storage FlashArray.
Will return False if target volume already exists and
overwrite is not specified, or selected snapshot doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of volume snapshot
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_volume_create foo.bar clone overwrite=True
'''
array = _get_system()
source, suffix = name.split('.')
if _get_snapshot(source, suffix, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_clone(name, target, overwrite=False):
'''
Clone an existing volume on a Pure Storage FlashArray.
Will return False if source volume doesn't exist, or
target volume already exists and overwrite not specified.
.. versionadded:: 2018.3.0
name : string
name of volume
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_clone foo bar overwrite=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_attach(name, host):
'''
Attach a volume to a host on a Pure Storage FlashArray.
Host and volume must exist or else will return False.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_attach foo bar
'''
array = _get_system()
if _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.connect_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_detach(name, host):
'''
Detach a volume from a host on a Pure Storage FlashArray.
Will return False if either host or volume do not exist, or
if selected volume isn't already connected to the host.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_detach foo bar
'''
array = _get_system()
if _get_volume(name, array) is None or _get_host(host, array) is None:
return False
elif _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.disconnect_host(host, name)
return True
except purestorage.PureError:
return False
def host_create(name, iqn=None, wwn=None, nqn=None):
'''
Add a host on a Pure Storage FlashArray.
Will return False if host already exists, or the iSCSI or
Fibre Channel parameters are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host (truncated to 63 characters)
iqn : string
iSCSI IQN of host
nqn : string
NVMeF NQN of host
wwn : string
Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_create foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_host(name, array) is None:
try:
array.create_host(name)
except purestorage.PureError:
return False
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
array.delete_host(name)
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
array.delete_host(name)
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
array.delete_host(name)
return False
else:
return False
return True
def host_update(name, iqn=None, wwn=None, nqn=None):
'''
Update a hosts port definitions on a Pure Storage FlashArray.
Will return False if new port definitions are already in use
by another host, or are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host
nqn : string
Additional NVMeF NQN of host
iqn : string
Additional iSCSI IQN of host
wwn : string
Additional Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_update foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if _get_host(name, array) is not None:
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
return False
return True
else:
return False
def host_delete(name):
'''
Delete a host on a Pure Storage FlashArray (detaches all volumes).
Will return False if the host doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_delete foo
'''
array = _get_system()
if _get_host(name, array) is not None:
for vol in array.list_host_connections(name):
try:
array.disconnect_host(name, vol['vol'])
except purestorage.PureError:
return False
try:
array.delete_host(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_create(name, host=None, volume=None):
'''
Create a hostgroup on a Pure Storage FlashArray.
Will return False if hostgroup already exists, or if
named host or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup (truncated to 63 characters)
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_create foo host=bar volume=vol
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_hgroup(name, array) is None:
try:
array.create_hgroup(name)
except purestorage.PureError:
return False
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
hg_delete(name)
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
hg_delete(name)
return False
else:
hg_delete(name)
return False
return True
else:
return False
def hg_update(name, host=None, volume=None):
'''
Adds entries to a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup doesn't exist, or host
or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_update foo host=bar volume=vol
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
return False
else:
return False
return True
else:
return False
def hg_delete(name):
'''
Delete a hostgroup on a Pure Storage FlashArray (removes all volumes and hosts).
Will return False is hostgroup is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_delete foo
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
for vol in array.list_hgroup_connections(name):
try:
array.disconnect_hgroup(name, vol['vol'])
except purestorage.PureError:
return False
host = array.get_hgroup(name)
try:
array.set_hgroup(name, remhostlist=host['hosts'])
array.delete_hgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_remove(name, volume=None, host=None):
'''
Remove a host and/or volume from a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup does not exist, or named host or volume are
not in the hostgroup.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
volume : string
name of volume to remove from hostgroup
host : string
name of host to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_remove foo volume=test host=bar
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if volume is not None:
if _get_volume(volume, array):
for temp in array.list_hgroup_connections(name):
if temp['vol'] == volume:
try:
array.disconnect_hgroup(name, volume)
return True
except purestorage.PureError:
return False
return False
else:
return False
if host is not None:
if _get_host(host, array):
temp = _get_host(host, array)
if temp['hgroup'] == name:
try:
array.set_hgroup(name, remhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
if host is None and volume is None:
return False
else:
return False
def pg_create(name, hostgroup=None, host=None, volume=None, enabled=True):
'''
Create a protection group on a Pure Storage FlashArray.
Will return False is the following cases:
* Protection Grop already exists
* Protection Group in a deleted state
* More than one type is specified - protection groups are for only
hostgroups, hosts or volumes
* Named type for protection group does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_create foo [hostgroup=foo | host=bar | volume=vol] enabled=[true | false]
'''
array = _get_system()
if hostgroup is None and host is None and volume is None:
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
return False
elif __utils__['value.xor'](hostgroup, host, volume):
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
except purestorage.PureError:
pg_delete(name)
return False
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
else:
return False
else:
return False
def pg_update(name, hostgroup=None, host=None, volume=None):
'''
Update a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Incorrect type selected for current protection group type
* Specified type does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_update foo [hostgroup=foo | host=bar | volume=vol]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.add_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.add_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.add_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
if pgroup['hgroups'] is None and pgroup['hosts'] is None and pgroup['volumes'] is None:
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
def pg_delete(name, eradicate=False):
'''
Delete a protecton group on a Pure Storage FlashArray.
Will return False if protection group is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_delete foo
'''
array = _get_system()
if _get_pgroup(name, array) is not None:
try:
array.destroy_pgroup(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def pg_eradicate(name):
'''
Eradicate a deleted protecton group on a Pure Storage FlashArray.
Will return False if protection group is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_eradicate foo
'''
array = _get_system()
if _get_deleted_pgroup(name, array) is not None:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def pg_remove(name, hostgroup=None, host=None, volume=None):
'''
Remove a hostgroup, host or volume from a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Specified type is not currently associated with the protection group
.. versionadded:: 2018.3.0
name : string
name of hostgroup
hostgroup : string
name of hostgroup to remove from protection group
host : string
name of host to remove from hostgroup
volume : string
name of volume to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_remove foo [hostgroup=bar | host=test | volume=bar]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.remove_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.remove_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.remove_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
|
saltstack/salt
|
salt/modules/purefa.py
|
_get_snapshot
|
python
|
def _get_snapshot(name, suffix, array):
'''Private function to check snapshot'''
snapshot = name + '.' + suffix
try:
for snap in array.get_volume(name, snap=True):
if snap['name'] == snapshot:
return snapshot
except purestorage.PureError:
return None
|
Private function to check snapshot
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/purefa.py#L150-L158
| null |
# -*- coding: utf-8 -*-
##
# Copyright 2017 Pure Storage Inc
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Management of Pure Storage FlashArray
Installation Prerequisites
--------------------------
- You will need the ``purestorage`` python package in your python installation
path that is running salt.
.. code-block:: bash
pip install purestorage
- Configure Pure Storage FlashArray authentication. Use one of the following
three methods.
1) From the minion config
.. code-block:: yaml
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
:maintainer: Simon Dodsley (simon@purestorage.com)
:maturity: new
:requires: purestorage
:platform: all
.. versionadded:: 2018.3.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import platform
from datetime import datetime
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Import 3rd party modules
try:
import purestorage
HAS_PURESTORAGE = True
except ImportError:
HAS_PURESTORAGE = False
__docformat__ = 'restructuredtext en'
VERSION = '1.0.0'
USER_AGENT_BASE = 'Salt'
__virtualname__ = 'purefa'
# Default symbols to use for passwords. Avoids visually confusing characters.
# ~6 bits per symbol
DEFAULT_PASSWORD_SYMBOLS = ('23456789', # Removed: 0,1
'ABCDEFGHJKLMNPQRSTUVWXYZ', # Removed: I, O
'abcdefghijkmnopqrstuvwxyz') # Removed: l
def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURESTORAGE:
return __virtualname__
return (False, 'purefa execution module not loaded: purestorage python library not available.')
def _get_system():
'''
Get Pure Storage FlashArray configuration
1) From the minion config
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
'''
agent = {'base': USER_AGENT_BASE,
'class': __name__,
'version': VERSION,
'platform': platform.platform()
}
user_agent = '{base} {class}/{version} ({platform})'.format(**agent)
try:
array = __opts__['pure_tags']['fa'].get('san_ip')
api = __opts__['pure_tags']['fa'].get('api_token')
if array and api:
system = purestorage.FlashArray(array, api_token=api, user_agent=user_agent)
except (KeyError, NameError, TypeError):
try:
san_ip = os.environ.get('PUREFA_IP')
api_token = os.environ.get('PUREFA_API')
system = purestorage.FlashArray(san_ip,
api_token=api_token,
user_agent=user_agent)
except (ValueError, KeyError, NameError):
try:
system = purestorage.FlashArray(__pillar__['PUREFA_IP'],
api_token=__pillar__['PUREFA_API'],
user_agent=user_agent)
except (KeyError, NameError):
raise CommandExecutionError('No Pure Storage FlashArray credentials found.')
try:
system.get()
except Exception:
raise CommandExecutionError('Pure Storage FlashArray authentication failed.')
return system
def _get_volume(name, array):
'''Private function to check volume'''
try:
return array.get_volume(name)
except purestorage.PureError:
return None
def _get_deleted_volume(name, array):
'''Private function to check deleted volume'''
try:
return array.get_volume(name, pending='true')
except purestorage.PureError:
return None
def _get_pgroup(name, array):
'''Private function to check protection group'''
pgroup = None
for temp in array.list_pgroups():
if temp['name'] == name:
pgroup = temp
break
return pgroup
def _get_deleted_pgroup(name, array):
'''Private function to check deleted protection group'''
try:
return array.get_pgroup(name, pending='true')
except purestorage.PureError:
return None
def _get_hgroup(name, array):
'''Private function to check hostgroup'''
hostgroup = None
for temp in array.list_hgroups():
if temp['name'] == name:
hostgroup = temp
break
return hostgroup
def _get_host(name, array):
'''Private function to check host'''
host = None
for temp in array.list_hosts():
if temp['name'] == name:
host = temp
break
return host
def snap_create(name, suffix=None):
'''
Create a volume snapshot on a Pure Storage FlashArray.
Will return False is volume selected to snap does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume to snapshot
suffix : string
if specificed forces snapshot name suffix. If not specified defaults to timestamp.
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_create foo
salt '*' purefa.snap_create foo suffix=bar
'''
array = _get_system()
if suffix is None:
suffix = 'snap-' + six.text_type((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds())
suffix = suffix.replace('.', '')
if _get_volume(name, array) is not None:
try:
array.create_snapshot(name, suffix=suffix)
return True
except purestorage.PureError:
return False
else:
return False
def snap_delete(name, suffix=None, eradicate=False):
'''
Delete a volume snapshot on a Pure Storage FlashArray.
Will return False if selected snapshot does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
eradicate : boolean
Eradicate snapshot after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_delete foo suffix=snap eradicate=True
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
try:
snapname = name + '.' + suffix
array.destroy_volume(snapname)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def snap_eradicate(name, suffix=None):
'''
Eradicate a deleted volume snapshot on a Pure Storage FlashArray.
Will return False if snapshot is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_eradicate foo suffix=snap
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
snapname = name + '.' + suffix
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return False
def volume_create(name, size=None):
'''
Create a volume on a Pure Storage FlashArray.
Will return False if volume already exists.
.. versionadded:: 2018.3.0
name : string
name of volume (truncated to 63 characters)
size : string
if specificed capacity of volume. If not specified default to 1G.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_create foo
salt '*' purefa.volume_create foo size=10T
'''
if len(name) > 63:
name = name[0:63]
array = _get_system()
if _get_volume(name, array) is None:
if size is None:
size = '1G'
try:
array.create_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
def volume_delete(name, eradicate=False):
'''
Delete a volume on a Pure Storage FlashArray.
Will return False if volume doesn't exist is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
eradicate : boolean
Eradicate volume after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_delete foo eradicate=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
try:
array.destroy_volume(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def volume_eradicate(name):
'''
Eradicate a deleted volume on a Pure Storage FlashArray.
Will return False is volume is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_eradicate foo
'''
array = _get_system()
if _get_deleted_volume(name, array) is not None:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_extend(name, size):
'''
Extend an existing volume on a Pure Storage FlashArray.
Will return False if new size is less than or equal to existing size.
.. versionadded:: 2018.3.0
name : string
name of volume
size : string
New capacity of volume.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_extend foo 10T
'''
array = _get_system()
vol = _get_volume(name, array)
if vol is not None:
if __utils__['stringutils.human_to_bytes'](size) > vol['size']:
try:
array.extend_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def snap_volume_create(name, target, overwrite=False):
'''
Create R/W volume from snapshot on a Pure Storage FlashArray.
Will return False if target volume already exists and
overwrite is not specified, or selected snapshot doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of volume snapshot
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_volume_create foo.bar clone overwrite=True
'''
array = _get_system()
source, suffix = name.split('.')
if _get_snapshot(source, suffix, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_clone(name, target, overwrite=False):
'''
Clone an existing volume on a Pure Storage FlashArray.
Will return False if source volume doesn't exist, or
target volume already exists and overwrite not specified.
.. versionadded:: 2018.3.0
name : string
name of volume
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_clone foo bar overwrite=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_attach(name, host):
'''
Attach a volume to a host on a Pure Storage FlashArray.
Host and volume must exist or else will return False.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_attach foo bar
'''
array = _get_system()
if _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.connect_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_detach(name, host):
'''
Detach a volume from a host on a Pure Storage FlashArray.
Will return False if either host or volume do not exist, or
if selected volume isn't already connected to the host.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_detach foo bar
'''
array = _get_system()
if _get_volume(name, array) is None or _get_host(host, array) is None:
return False
elif _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.disconnect_host(host, name)
return True
except purestorage.PureError:
return False
def host_create(name, iqn=None, wwn=None, nqn=None):
'''
Add a host on a Pure Storage FlashArray.
Will return False if host already exists, or the iSCSI or
Fibre Channel parameters are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host (truncated to 63 characters)
iqn : string
iSCSI IQN of host
nqn : string
NVMeF NQN of host
wwn : string
Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_create foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_host(name, array) is None:
try:
array.create_host(name)
except purestorage.PureError:
return False
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
array.delete_host(name)
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
array.delete_host(name)
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
array.delete_host(name)
return False
else:
return False
return True
def host_update(name, iqn=None, wwn=None, nqn=None):
'''
Update a hosts port definitions on a Pure Storage FlashArray.
Will return False if new port definitions are already in use
by another host, or are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host
nqn : string
Additional NVMeF NQN of host
iqn : string
Additional iSCSI IQN of host
wwn : string
Additional Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_update foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if _get_host(name, array) is not None:
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
return False
return True
else:
return False
def host_delete(name):
'''
Delete a host on a Pure Storage FlashArray (detaches all volumes).
Will return False if the host doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_delete foo
'''
array = _get_system()
if _get_host(name, array) is not None:
for vol in array.list_host_connections(name):
try:
array.disconnect_host(name, vol['vol'])
except purestorage.PureError:
return False
try:
array.delete_host(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_create(name, host=None, volume=None):
'''
Create a hostgroup on a Pure Storage FlashArray.
Will return False if hostgroup already exists, or if
named host or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup (truncated to 63 characters)
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_create foo host=bar volume=vol
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_hgroup(name, array) is None:
try:
array.create_hgroup(name)
except purestorage.PureError:
return False
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
hg_delete(name)
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
hg_delete(name)
return False
else:
hg_delete(name)
return False
return True
else:
return False
def hg_update(name, host=None, volume=None):
'''
Adds entries to a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup doesn't exist, or host
or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_update foo host=bar volume=vol
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
return False
else:
return False
return True
else:
return False
def hg_delete(name):
'''
Delete a hostgroup on a Pure Storage FlashArray (removes all volumes and hosts).
Will return False is hostgroup is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_delete foo
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
for vol in array.list_hgroup_connections(name):
try:
array.disconnect_hgroup(name, vol['vol'])
except purestorage.PureError:
return False
host = array.get_hgroup(name)
try:
array.set_hgroup(name, remhostlist=host['hosts'])
array.delete_hgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_remove(name, volume=None, host=None):
'''
Remove a host and/or volume from a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup does not exist, or named host or volume are
not in the hostgroup.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
volume : string
name of volume to remove from hostgroup
host : string
name of host to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_remove foo volume=test host=bar
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if volume is not None:
if _get_volume(volume, array):
for temp in array.list_hgroup_connections(name):
if temp['vol'] == volume:
try:
array.disconnect_hgroup(name, volume)
return True
except purestorage.PureError:
return False
return False
else:
return False
if host is not None:
if _get_host(host, array):
temp = _get_host(host, array)
if temp['hgroup'] == name:
try:
array.set_hgroup(name, remhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
if host is None and volume is None:
return False
else:
return False
def pg_create(name, hostgroup=None, host=None, volume=None, enabled=True):
'''
Create a protection group on a Pure Storage FlashArray.
Will return False is the following cases:
* Protection Grop already exists
* Protection Group in a deleted state
* More than one type is specified - protection groups are for only
hostgroups, hosts or volumes
* Named type for protection group does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_create foo [hostgroup=foo | host=bar | volume=vol] enabled=[true | false]
'''
array = _get_system()
if hostgroup is None and host is None and volume is None:
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
return False
elif __utils__['value.xor'](hostgroup, host, volume):
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
except purestorage.PureError:
pg_delete(name)
return False
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
else:
return False
else:
return False
def pg_update(name, hostgroup=None, host=None, volume=None):
'''
Update a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Incorrect type selected for current protection group type
* Specified type does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_update foo [hostgroup=foo | host=bar | volume=vol]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.add_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.add_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.add_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
if pgroup['hgroups'] is None and pgroup['hosts'] is None and pgroup['volumes'] is None:
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
def pg_delete(name, eradicate=False):
'''
Delete a protecton group on a Pure Storage FlashArray.
Will return False if protection group is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_delete foo
'''
array = _get_system()
if _get_pgroup(name, array) is not None:
try:
array.destroy_pgroup(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def pg_eradicate(name):
'''
Eradicate a deleted protecton group on a Pure Storage FlashArray.
Will return False if protection group is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_eradicate foo
'''
array = _get_system()
if _get_deleted_pgroup(name, array) is not None:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def pg_remove(name, hostgroup=None, host=None, volume=None):
'''
Remove a hostgroup, host or volume from a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Specified type is not currently associated with the protection group
.. versionadded:: 2018.3.0
name : string
name of hostgroup
hostgroup : string
name of hostgroup to remove from protection group
host : string
name of host to remove from hostgroup
volume : string
name of volume to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_remove foo [hostgroup=bar | host=test | volume=bar]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.remove_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.remove_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.remove_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
|
saltstack/salt
|
salt/modules/purefa.py
|
_get_pgroup
|
python
|
def _get_pgroup(name, array):
'''Private function to check protection group'''
pgroup = None
for temp in array.list_pgroups():
if temp['name'] == name:
pgroup = temp
break
return pgroup
|
Private function to check protection group
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/purefa.py#L169-L176
| null |
# -*- coding: utf-8 -*-
##
# Copyright 2017 Pure Storage Inc
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Management of Pure Storage FlashArray
Installation Prerequisites
--------------------------
- You will need the ``purestorage`` python package in your python installation
path that is running salt.
.. code-block:: bash
pip install purestorage
- Configure Pure Storage FlashArray authentication. Use one of the following
three methods.
1) From the minion config
.. code-block:: yaml
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
:maintainer: Simon Dodsley (simon@purestorage.com)
:maturity: new
:requires: purestorage
:platform: all
.. versionadded:: 2018.3.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import platform
from datetime import datetime
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Import 3rd party modules
try:
import purestorage
HAS_PURESTORAGE = True
except ImportError:
HAS_PURESTORAGE = False
__docformat__ = 'restructuredtext en'
VERSION = '1.0.0'
USER_AGENT_BASE = 'Salt'
__virtualname__ = 'purefa'
# Default symbols to use for passwords. Avoids visually confusing characters.
# ~6 bits per symbol
DEFAULT_PASSWORD_SYMBOLS = ('23456789', # Removed: 0,1
'ABCDEFGHJKLMNPQRSTUVWXYZ', # Removed: I, O
'abcdefghijkmnopqrstuvwxyz') # Removed: l
def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURESTORAGE:
return __virtualname__
return (False, 'purefa execution module not loaded: purestorage python library not available.')
def _get_system():
'''
Get Pure Storage FlashArray configuration
1) From the minion config
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
'''
agent = {'base': USER_AGENT_BASE,
'class': __name__,
'version': VERSION,
'platform': platform.platform()
}
user_agent = '{base} {class}/{version} ({platform})'.format(**agent)
try:
array = __opts__['pure_tags']['fa'].get('san_ip')
api = __opts__['pure_tags']['fa'].get('api_token')
if array and api:
system = purestorage.FlashArray(array, api_token=api, user_agent=user_agent)
except (KeyError, NameError, TypeError):
try:
san_ip = os.environ.get('PUREFA_IP')
api_token = os.environ.get('PUREFA_API')
system = purestorage.FlashArray(san_ip,
api_token=api_token,
user_agent=user_agent)
except (ValueError, KeyError, NameError):
try:
system = purestorage.FlashArray(__pillar__['PUREFA_IP'],
api_token=__pillar__['PUREFA_API'],
user_agent=user_agent)
except (KeyError, NameError):
raise CommandExecutionError('No Pure Storage FlashArray credentials found.')
try:
system.get()
except Exception:
raise CommandExecutionError('Pure Storage FlashArray authentication failed.')
return system
def _get_volume(name, array):
'''Private function to check volume'''
try:
return array.get_volume(name)
except purestorage.PureError:
return None
def _get_snapshot(name, suffix, array):
'''Private function to check snapshot'''
snapshot = name + '.' + suffix
try:
for snap in array.get_volume(name, snap=True):
if snap['name'] == snapshot:
return snapshot
except purestorage.PureError:
return None
def _get_deleted_volume(name, array):
'''Private function to check deleted volume'''
try:
return array.get_volume(name, pending='true')
except purestorage.PureError:
return None
def _get_deleted_pgroup(name, array):
'''Private function to check deleted protection group'''
try:
return array.get_pgroup(name, pending='true')
except purestorage.PureError:
return None
def _get_hgroup(name, array):
'''Private function to check hostgroup'''
hostgroup = None
for temp in array.list_hgroups():
if temp['name'] == name:
hostgroup = temp
break
return hostgroup
def _get_host(name, array):
'''Private function to check host'''
host = None
for temp in array.list_hosts():
if temp['name'] == name:
host = temp
break
return host
def snap_create(name, suffix=None):
'''
Create a volume snapshot on a Pure Storage FlashArray.
Will return False is volume selected to snap does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume to snapshot
suffix : string
if specificed forces snapshot name suffix. If not specified defaults to timestamp.
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_create foo
salt '*' purefa.snap_create foo suffix=bar
'''
array = _get_system()
if suffix is None:
suffix = 'snap-' + six.text_type((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds())
suffix = suffix.replace('.', '')
if _get_volume(name, array) is not None:
try:
array.create_snapshot(name, suffix=suffix)
return True
except purestorage.PureError:
return False
else:
return False
def snap_delete(name, suffix=None, eradicate=False):
'''
Delete a volume snapshot on a Pure Storage FlashArray.
Will return False if selected snapshot does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
eradicate : boolean
Eradicate snapshot after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_delete foo suffix=snap eradicate=True
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
try:
snapname = name + '.' + suffix
array.destroy_volume(snapname)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def snap_eradicate(name, suffix=None):
'''
Eradicate a deleted volume snapshot on a Pure Storage FlashArray.
Will return False if snapshot is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_eradicate foo suffix=snap
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
snapname = name + '.' + suffix
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return False
def volume_create(name, size=None):
'''
Create a volume on a Pure Storage FlashArray.
Will return False if volume already exists.
.. versionadded:: 2018.3.0
name : string
name of volume (truncated to 63 characters)
size : string
if specificed capacity of volume. If not specified default to 1G.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_create foo
salt '*' purefa.volume_create foo size=10T
'''
if len(name) > 63:
name = name[0:63]
array = _get_system()
if _get_volume(name, array) is None:
if size is None:
size = '1G'
try:
array.create_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
def volume_delete(name, eradicate=False):
'''
Delete a volume on a Pure Storage FlashArray.
Will return False if volume doesn't exist is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
eradicate : boolean
Eradicate volume after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_delete foo eradicate=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
try:
array.destroy_volume(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def volume_eradicate(name):
'''
Eradicate a deleted volume on a Pure Storage FlashArray.
Will return False is volume is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_eradicate foo
'''
array = _get_system()
if _get_deleted_volume(name, array) is not None:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_extend(name, size):
'''
Extend an existing volume on a Pure Storage FlashArray.
Will return False if new size is less than or equal to existing size.
.. versionadded:: 2018.3.0
name : string
name of volume
size : string
New capacity of volume.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_extend foo 10T
'''
array = _get_system()
vol = _get_volume(name, array)
if vol is not None:
if __utils__['stringutils.human_to_bytes'](size) > vol['size']:
try:
array.extend_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def snap_volume_create(name, target, overwrite=False):
'''
Create R/W volume from snapshot on a Pure Storage FlashArray.
Will return False if target volume already exists and
overwrite is not specified, or selected snapshot doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of volume snapshot
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_volume_create foo.bar clone overwrite=True
'''
array = _get_system()
source, suffix = name.split('.')
if _get_snapshot(source, suffix, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_clone(name, target, overwrite=False):
'''
Clone an existing volume on a Pure Storage FlashArray.
Will return False if source volume doesn't exist, or
target volume already exists and overwrite not specified.
.. versionadded:: 2018.3.0
name : string
name of volume
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_clone foo bar overwrite=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_attach(name, host):
'''
Attach a volume to a host on a Pure Storage FlashArray.
Host and volume must exist or else will return False.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_attach foo bar
'''
array = _get_system()
if _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.connect_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_detach(name, host):
'''
Detach a volume from a host on a Pure Storage FlashArray.
Will return False if either host or volume do not exist, or
if selected volume isn't already connected to the host.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_detach foo bar
'''
array = _get_system()
if _get_volume(name, array) is None or _get_host(host, array) is None:
return False
elif _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.disconnect_host(host, name)
return True
except purestorage.PureError:
return False
def host_create(name, iqn=None, wwn=None, nqn=None):
'''
Add a host on a Pure Storage FlashArray.
Will return False if host already exists, or the iSCSI or
Fibre Channel parameters are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host (truncated to 63 characters)
iqn : string
iSCSI IQN of host
nqn : string
NVMeF NQN of host
wwn : string
Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_create foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_host(name, array) is None:
try:
array.create_host(name)
except purestorage.PureError:
return False
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
array.delete_host(name)
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
array.delete_host(name)
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
array.delete_host(name)
return False
else:
return False
return True
def host_update(name, iqn=None, wwn=None, nqn=None):
'''
Update a hosts port definitions on a Pure Storage FlashArray.
Will return False if new port definitions are already in use
by another host, or are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host
nqn : string
Additional NVMeF NQN of host
iqn : string
Additional iSCSI IQN of host
wwn : string
Additional Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_update foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if _get_host(name, array) is not None:
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
return False
return True
else:
return False
def host_delete(name):
'''
Delete a host on a Pure Storage FlashArray (detaches all volumes).
Will return False if the host doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_delete foo
'''
array = _get_system()
if _get_host(name, array) is not None:
for vol in array.list_host_connections(name):
try:
array.disconnect_host(name, vol['vol'])
except purestorage.PureError:
return False
try:
array.delete_host(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_create(name, host=None, volume=None):
'''
Create a hostgroup on a Pure Storage FlashArray.
Will return False if hostgroup already exists, or if
named host or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup (truncated to 63 characters)
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_create foo host=bar volume=vol
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_hgroup(name, array) is None:
try:
array.create_hgroup(name)
except purestorage.PureError:
return False
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
hg_delete(name)
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
hg_delete(name)
return False
else:
hg_delete(name)
return False
return True
else:
return False
def hg_update(name, host=None, volume=None):
'''
Adds entries to a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup doesn't exist, or host
or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_update foo host=bar volume=vol
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
return False
else:
return False
return True
else:
return False
def hg_delete(name):
'''
Delete a hostgroup on a Pure Storage FlashArray (removes all volumes and hosts).
Will return False is hostgroup is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_delete foo
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
for vol in array.list_hgroup_connections(name):
try:
array.disconnect_hgroup(name, vol['vol'])
except purestorage.PureError:
return False
host = array.get_hgroup(name)
try:
array.set_hgroup(name, remhostlist=host['hosts'])
array.delete_hgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_remove(name, volume=None, host=None):
'''
Remove a host and/or volume from a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup does not exist, or named host or volume are
not in the hostgroup.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
volume : string
name of volume to remove from hostgroup
host : string
name of host to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_remove foo volume=test host=bar
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if volume is not None:
if _get_volume(volume, array):
for temp in array.list_hgroup_connections(name):
if temp['vol'] == volume:
try:
array.disconnect_hgroup(name, volume)
return True
except purestorage.PureError:
return False
return False
else:
return False
if host is not None:
if _get_host(host, array):
temp = _get_host(host, array)
if temp['hgroup'] == name:
try:
array.set_hgroup(name, remhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
if host is None and volume is None:
return False
else:
return False
def pg_create(name, hostgroup=None, host=None, volume=None, enabled=True):
'''
Create a protection group on a Pure Storage FlashArray.
Will return False is the following cases:
* Protection Grop already exists
* Protection Group in a deleted state
* More than one type is specified - protection groups are for only
hostgroups, hosts or volumes
* Named type for protection group does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_create foo [hostgroup=foo | host=bar | volume=vol] enabled=[true | false]
'''
array = _get_system()
if hostgroup is None and host is None and volume is None:
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
return False
elif __utils__['value.xor'](hostgroup, host, volume):
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
except purestorage.PureError:
pg_delete(name)
return False
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
else:
return False
else:
return False
def pg_update(name, hostgroup=None, host=None, volume=None):
'''
Update a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Incorrect type selected for current protection group type
* Specified type does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_update foo [hostgroup=foo | host=bar | volume=vol]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.add_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.add_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.add_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
if pgroup['hgroups'] is None and pgroup['hosts'] is None and pgroup['volumes'] is None:
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
def pg_delete(name, eradicate=False):
'''
Delete a protecton group on a Pure Storage FlashArray.
Will return False if protection group is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_delete foo
'''
array = _get_system()
if _get_pgroup(name, array) is not None:
try:
array.destroy_pgroup(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def pg_eradicate(name):
'''
Eradicate a deleted protecton group on a Pure Storage FlashArray.
Will return False if protection group is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_eradicate foo
'''
array = _get_system()
if _get_deleted_pgroup(name, array) is not None:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def pg_remove(name, hostgroup=None, host=None, volume=None):
'''
Remove a hostgroup, host or volume from a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Specified type is not currently associated with the protection group
.. versionadded:: 2018.3.0
name : string
name of hostgroup
hostgroup : string
name of hostgroup to remove from protection group
host : string
name of host to remove from hostgroup
volume : string
name of volume to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_remove foo [hostgroup=bar | host=test | volume=bar]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.remove_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.remove_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.remove_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
|
saltstack/salt
|
salt/modules/purefa.py
|
_get_hgroup
|
python
|
def _get_hgroup(name, array):
'''Private function to check hostgroup'''
hostgroup = None
for temp in array.list_hgroups():
if temp['name'] == name:
hostgroup = temp
break
return hostgroup
|
Private function to check hostgroup
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/purefa.py#L187-L194
| null |
# -*- coding: utf-8 -*-
##
# Copyright 2017 Pure Storage Inc
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Management of Pure Storage FlashArray
Installation Prerequisites
--------------------------
- You will need the ``purestorage`` python package in your python installation
path that is running salt.
.. code-block:: bash
pip install purestorage
- Configure Pure Storage FlashArray authentication. Use one of the following
three methods.
1) From the minion config
.. code-block:: yaml
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
:maintainer: Simon Dodsley (simon@purestorage.com)
:maturity: new
:requires: purestorage
:platform: all
.. versionadded:: 2018.3.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import platform
from datetime import datetime
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Import 3rd party modules
try:
import purestorage
HAS_PURESTORAGE = True
except ImportError:
HAS_PURESTORAGE = False
__docformat__ = 'restructuredtext en'
VERSION = '1.0.0'
USER_AGENT_BASE = 'Salt'
__virtualname__ = 'purefa'
# Default symbols to use for passwords. Avoids visually confusing characters.
# ~6 bits per symbol
DEFAULT_PASSWORD_SYMBOLS = ('23456789', # Removed: 0,1
'ABCDEFGHJKLMNPQRSTUVWXYZ', # Removed: I, O
'abcdefghijkmnopqrstuvwxyz') # Removed: l
def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURESTORAGE:
return __virtualname__
return (False, 'purefa execution module not loaded: purestorage python library not available.')
def _get_system():
'''
Get Pure Storage FlashArray configuration
1) From the minion config
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
'''
agent = {'base': USER_AGENT_BASE,
'class': __name__,
'version': VERSION,
'platform': platform.platform()
}
user_agent = '{base} {class}/{version} ({platform})'.format(**agent)
try:
array = __opts__['pure_tags']['fa'].get('san_ip')
api = __opts__['pure_tags']['fa'].get('api_token')
if array and api:
system = purestorage.FlashArray(array, api_token=api, user_agent=user_agent)
except (KeyError, NameError, TypeError):
try:
san_ip = os.environ.get('PUREFA_IP')
api_token = os.environ.get('PUREFA_API')
system = purestorage.FlashArray(san_ip,
api_token=api_token,
user_agent=user_agent)
except (ValueError, KeyError, NameError):
try:
system = purestorage.FlashArray(__pillar__['PUREFA_IP'],
api_token=__pillar__['PUREFA_API'],
user_agent=user_agent)
except (KeyError, NameError):
raise CommandExecutionError('No Pure Storage FlashArray credentials found.')
try:
system.get()
except Exception:
raise CommandExecutionError('Pure Storage FlashArray authentication failed.')
return system
def _get_volume(name, array):
'''Private function to check volume'''
try:
return array.get_volume(name)
except purestorage.PureError:
return None
def _get_snapshot(name, suffix, array):
'''Private function to check snapshot'''
snapshot = name + '.' + suffix
try:
for snap in array.get_volume(name, snap=True):
if snap['name'] == snapshot:
return snapshot
except purestorage.PureError:
return None
def _get_deleted_volume(name, array):
'''Private function to check deleted volume'''
try:
return array.get_volume(name, pending='true')
except purestorage.PureError:
return None
def _get_pgroup(name, array):
'''Private function to check protection group'''
pgroup = None
for temp in array.list_pgroups():
if temp['name'] == name:
pgroup = temp
break
return pgroup
def _get_deleted_pgroup(name, array):
'''Private function to check deleted protection group'''
try:
return array.get_pgroup(name, pending='true')
except purestorage.PureError:
return None
def _get_host(name, array):
'''Private function to check host'''
host = None
for temp in array.list_hosts():
if temp['name'] == name:
host = temp
break
return host
def snap_create(name, suffix=None):
'''
Create a volume snapshot on a Pure Storage FlashArray.
Will return False is volume selected to snap does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume to snapshot
suffix : string
if specificed forces snapshot name suffix. If not specified defaults to timestamp.
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_create foo
salt '*' purefa.snap_create foo suffix=bar
'''
array = _get_system()
if suffix is None:
suffix = 'snap-' + six.text_type((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds())
suffix = suffix.replace('.', '')
if _get_volume(name, array) is not None:
try:
array.create_snapshot(name, suffix=suffix)
return True
except purestorage.PureError:
return False
else:
return False
def snap_delete(name, suffix=None, eradicate=False):
'''
Delete a volume snapshot on a Pure Storage FlashArray.
Will return False if selected snapshot does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
eradicate : boolean
Eradicate snapshot after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_delete foo suffix=snap eradicate=True
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
try:
snapname = name + '.' + suffix
array.destroy_volume(snapname)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def snap_eradicate(name, suffix=None):
'''
Eradicate a deleted volume snapshot on a Pure Storage FlashArray.
Will return False if snapshot is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_eradicate foo suffix=snap
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
snapname = name + '.' + suffix
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return False
def volume_create(name, size=None):
'''
Create a volume on a Pure Storage FlashArray.
Will return False if volume already exists.
.. versionadded:: 2018.3.0
name : string
name of volume (truncated to 63 characters)
size : string
if specificed capacity of volume. If not specified default to 1G.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_create foo
salt '*' purefa.volume_create foo size=10T
'''
if len(name) > 63:
name = name[0:63]
array = _get_system()
if _get_volume(name, array) is None:
if size is None:
size = '1G'
try:
array.create_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
def volume_delete(name, eradicate=False):
'''
Delete a volume on a Pure Storage FlashArray.
Will return False if volume doesn't exist is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
eradicate : boolean
Eradicate volume after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_delete foo eradicate=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
try:
array.destroy_volume(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def volume_eradicate(name):
'''
Eradicate a deleted volume on a Pure Storage FlashArray.
Will return False is volume is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_eradicate foo
'''
array = _get_system()
if _get_deleted_volume(name, array) is not None:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_extend(name, size):
'''
Extend an existing volume on a Pure Storage FlashArray.
Will return False if new size is less than or equal to existing size.
.. versionadded:: 2018.3.0
name : string
name of volume
size : string
New capacity of volume.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_extend foo 10T
'''
array = _get_system()
vol = _get_volume(name, array)
if vol is not None:
if __utils__['stringutils.human_to_bytes'](size) > vol['size']:
try:
array.extend_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def snap_volume_create(name, target, overwrite=False):
'''
Create R/W volume from snapshot on a Pure Storage FlashArray.
Will return False if target volume already exists and
overwrite is not specified, or selected snapshot doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of volume snapshot
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_volume_create foo.bar clone overwrite=True
'''
array = _get_system()
source, suffix = name.split('.')
if _get_snapshot(source, suffix, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_clone(name, target, overwrite=False):
'''
Clone an existing volume on a Pure Storage FlashArray.
Will return False if source volume doesn't exist, or
target volume already exists and overwrite not specified.
.. versionadded:: 2018.3.0
name : string
name of volume
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_clone foo bar overwrite=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_attach(name, host):
'''
Attach a volume to a host on a Pure Storage FlashArray.
Host and volume must exist or else will return False.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_attach foo bar
'''
array = _get_system()
if _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.connect_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_detach(name, host):
'''
Detach a volume from a host on a Pure Storage FlashArray.
Will return False if either host or volume do not exist, or
if selected volume isn't already connected to the host.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_detach foo bar
'''
array = _get_system()
if _get_volume(name, array) is None or _get_host(host, array) is None:
return False
elif _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.disconnect_host(host, name)
return True
except purestorage.PureError:
return False
def host_create(name, iqn=None, wwn=None, nqn=None):
'''
Add a host on a Pure Storage FlashArray.
Will return False if host already exists, or the iSCSI or
Fibre Channel parameters are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host (truncated to 63 characters)
iqn : string
iSCSI IQN of host
nqn : string
NVMeF NQN of host
wwn : string
Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_create foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_host(name, array) is None:
try:
array.create_host(name)
except purestorage.PureError:
return False
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
array.delete_host(name)
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
array.delete_host(name)
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
array.delete_host(name)
return False
else:
return False
return True
def host_update(name, iqn=None, wwn=None, nqn=None):
'''
Update a hosts port definitions on a Pure Storage FlashArray.
Will return False if new port definitions are already in use
by another host, or are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host
nqn : string
Additional NVMeF NQN of host
iqn : string
Additional iSCSI IQN of host
wwn : string
Additional Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_update foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if _get_host(name, array) is not None:
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
return False
return True
else:
return False
def host_delete(name):
'''
Delete a host on a Pure Storage FlashArray (detaches all volumes).
Will return False if the host doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_delete foo
'''
array = _get_system()
if _get_host(name, array) is not None:
for vol in array.list_host_connections(name):
try:
array.disconnect_host(name, vol['vol'])
except purestorage.PureError:
return False
try:
array.delete_host(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_create(name, host=None, volume=None):
'''
Create a hostgroup on a Pure Storage FlashArray.
Will return False if hostgroup already exists, or if
named host or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup (truncated to 63 characters)
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_create foo host=bar volume=vol
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_hgroup(name, array) is None:
try:
array.create_hgroup(name)
except purestorage.PureError:
return False
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
hg_delete(name)
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
hg_delete(name)
return False
else:
hg_delete(name)
return False
return True
else:
return False
def hg_update(name, host=None, volume=None):
'''
Adds entries to a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup doesn't exist, or host
or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_update foo host=bar volume=vol
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
return False
else:
return False
return True
else:
return False
def hg_delete(name):
'''
Delete a hostgroup on a Pure Storage FlashArray (removes all volumes and hosts).
Will return False is hostgroup is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_delete foo
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
for vol in array.list_hgroup_connections(name):
try:
array.disconnect_hgroup(name, vol['vol'])
except purestorage.PureError:
return False
host = array.get_hgroup(name)
try:
array.set_hgroup(name, remhostlist=host['hosts'])
array.delete_hgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_remove(name, volume=None, host=None):
'''
Remove a host and/or volume from a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup does not exist, or named host or volume are
not in the hostgroup.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
volume : string
name of volume to remove from hostgroup
host : string
name of host to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_remove foo volume=test host=bar
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if volume is not None:
if _get_volume(volume, array):
for temp in array.list_hgroup_connections(name):
if temp['vol'] == volume:
try:
array.disconnect_hgroup(name, volume)
return True
except purestorage.PureError:
return False
return False
else:
return False
if host is not None:
if _get_host(host, array):
temp = _get_host(host, array)
if temp['hgroup'] == name:
try:
array.set_hgroup(name, remhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
if host is None and volume is None:
return False
else:
return False
def pg_create(name, hostgroup=None, host=None, volume=None, enabled=True):
'''
Create a protection group on a Pure Storage FlashArray.
Will return False is the following cases:
* Protection Grop already exists
* Protection Group in a deleted state
* More than one type is specified - protection groups are for only
hostgroups, hosts or volumes
* Named type for protection group does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_create foo [hostgroup=foo | host=bar | volume=vol] enabled=[true | false]
'''
array = _get_system()
if hostgroup is None and host is None and volume is None:
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
return False
elif __utils__['value.xor'](hostgroup, host, volume):
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
except purestorage.PureError:
pg_delete(name)
return False
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
else:
return False
else:
return False
def pg_update(name, hostgroup=None, host=None, volume=None):
'''
Update a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Incorrect type selected for current protection group type
* Specified type does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_update foo [hostgroup=foo | host=bar | volume=vol]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.add_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.add_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.add_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
if pgroup['hgroups'] is None and pgroup['hosts'] is None and pgroup['volumes'] is None:
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
def pg_delete(name, eradicate=False):
'''
Delete a protecton group on a Pure Storage FlashArray.
Will return False if protection group is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_delete foo
'''
array = _get_system()
if _get_pgroup(name, array) is not None:
try:
array.destroy_pgroup(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def pg_eradicate(name):
'''
Eradicate a deleted protecton group on a Pure Storage FlashArray.
Will return False if protection group is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_eradicate foo
'''
array = _get_system()
if _get_deleted_pgroup(name, array) is not None:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def pg_remove(name, hostgroup=None, host=None, volume=None):
'''
Remove a hostgroup, host or volume from a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Specified type is not currently associated with the protection group
.. versionadded:: 2018.3.0
name : string
name of hostgroup
hostgroup : string
name of hostgroup to remove from protection group
host : string
name of host to remove from hostgroup
volume : string
name of volume to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_remove foo [hostgroup=bar | host=test | volume=bar]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.remove_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.remove_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.remove_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
|
saltstack/salt
|
salt/modules/purefa.py
|
_get_host
|
python
|
def _get_host(name, array):
'''Private function to check host'''
host = None
for temp in array.list_hosts():
if temp['name'] == name:
host = temp
break
return host
|
Private function to check host
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/purefa.py#L197-L204
| null |
# -*- coding: utf-8 -*-
##
# Copyright 2017 Pure Storage Inc
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Management of Pure Storage FlashArray
Installation Prerequisites
--------------------------
- You will need the ``purestorage`` python package in your python installation
path that is running salt.
.. code-block:: bash
pip install purestorage
- Configure Pure Storage FlashArray authentication. Use one of the following
three methods.
1) From the minion config
.. code-block:: yaml
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
:maintainer: Simon Dodsley (simon@purestorage.com)
:maturity: new
:requires: purestorage
:platform: all
.. versionadded:: 2018.3.0
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import platform
from datetime import datetime
# Import Salt libs
from salt.ext import six
from salt.exceptions import CommandExecutionError
# Import 3rd party modules
try:
import purestorage
HAS_PURESTORAGE = True
except ImportError:
HAS_PURESTORAGE = False
__docformat__ = 'restructuredtext en'
VERSION = '1.0.0'
USER_AGENT_BASE = 'Salt'
__virtualname__ = 'purefa'
# Default symbols to use for passwords. Avoids visually confusing characters.
# ~6 bits per symbol
DEFAULT_PASSWORD_SYMBOLS = ('23456789', # Removed: 0,1
'ABCDEFGHJKLMNPQRSTUVWXYZ', # Removed: I, O
'abcdefghijkmnopqrstuvwxyz') # Removed: l
def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURESTORAGE:
return __virtualname__
return (False, 'purefa execution module not loaded: purestorage python library not available.')
def _get_system():
'''
Get Pure Storage FlashArray configuration
1) From the minion config
pure_tags:
fa:
san_ip: management vip or hostname for the FlashArray
api_token: A valid api token for the FlashArray being managed
2) From environment (PUREFA_IP and PUREFA_API)
3) From the pillar (PUREFA_IP and PUREFA_API)
'''
agent = {'base': USER_AGENT_BASE,
'class': __name__,
'version': VERSION,
'platform': platform.platform()
}
user_agent = '{base} {class}/{version} ({platform})'.format(**agent)
try:
array = __opts__['pure_tags']['fa'].get('san_ip')
api = __opts__['pure_tags']['fa'].get('api_token')
if array and api:
system = purestorage.FlashArray(array, api_token=api, user_agent=user_agent)
except (KeyError, NameError, TypeError):
try:
san_ip = os.environ.get('PUREFA_IP')
api_token = os.environ.get('PUREFA_API')
system = purestorage.FlashArray(san_ip,
api_token=api_token,
user_agent=user_agent)
except (ValueError, KeyError, NameError):
try:
system = purestorage.FlashArray(__pillar__['PUREFA_IP'],
api_token=__pillar__['PUREFA_API'],
user_agent=user_agent)
except (KeyError, NameError):
raise CommandExecutionError('No Pure Storage FlashArray credentials found.')
try:
system.get()
except Exception:
raise CommandExecutionError('Pure Storage FlashArray authentication failed.')
return system
def _get_volume(name, array):
'''Private function to check volume'''
try:
return array.get_volume(name)
except purestorage.PureError:
return None
def _get_snapshot(name, suffix, array):
'''Private function to check snapshot'''
snapshot = name + '.' + suffix
try:
for snap in array.get_volume(name, snap=True):
if snap['name'] == snapshot:
return snapshot
except purestorage.PureError:
return None
def _get_deleted_volume(name, array):
'''Private function to check deleted volume'''
try:
return array.get_volume(name, pending='true')
except purestorage.PureError:
return None
def _get_pgroup(name, array):
'''Private function to check protection group'''
pgroup = None
for temp in array.list_pgroups():
if temp['name'] == name:
pgroup = temp
break
return pgroup
def _get_deleted_pgroup(name, array):
'''Private function to check deleted protection group'''
try:
return array.get_pgroup(name, pending='true')
except purestorage.PureError:
return None
def _get_hgroup(name, array):
'''Private function to check hostgroup'''
hostgroup = None
for temp in array.list_hgroups():
if temp['name'] == name:
hostgroup = temp
break
return hostgroup
def snap_create(name, suffix=None):
'''
Create a volume snapshot on a Pure Storage FlashArray.
Will return False is volume selected to snap does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume to snapshot
suffix : string
if specificed forces snapshot name suffix. If not specified defaults to timestamp.
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_create foo
salt '*' purefa.snap_create foo suffix=bar
'''
array = _get_system()
if suffix is None:
suffix = 'snap-' + six.text_type((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds())
suffix = suffix.replace('.', '')
if _get_volume(name, array) is not None:
try:
array.create_snapshot(name, suffix=suffix)
return True
except purestorage.PureError:
return False
else:
return False
def snap_delete(name, suffix=None, eradicate=False):
'''
Delete a volume snapshot on a Pure Storage FlashArray.
Will return False if selected snapshot does not exist.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
eradicate : boolean
Eradicate snapshot after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_delete foo suffix=snap eradicate=True
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
try:
snapname = name + '.' + suffix
array.destroy_volume(snapname)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def snap_eradicate(name, suffix=None):
'''
Eradicate a deleted volume snapshot on a Pure Storage FlashArray.
Will return False if snapshot is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_eradicate foo suffix=snap
'''
array = _get_system()
if _get_snapshot(name, suffix, array) is not None:
snapname = name + '.' + suffix
try:
array.eradicate_volume(snapname)
return True
except purestorage.PureError:
return False
else:
return False
def volume_create(name, size=None):
'''
Create a volume on a Pure Storage FlashArray.
Will return False if volume already exists.
.. versionadded:: 2018.3.0
name : string
name of volume (truncated to 63 characters)
size : string
if specificed capacity of volume. If not specified default to 1G.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_create foo
salt '*' purefa.volume_create foo size=10T
'''
if len(name) > 63:
name = name[0:63]
array = _get_system()
if _get_volume(name, array) is None:
if size is None:
size = '1G'
try:
array.create_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
def volume_delete(name, eradicate=False):
'''
Delete a volume on a Pure Storage FlashArray.
Will return False if volume doesn't exist is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
eradicate : boolean
Eradicate volume after deletion if True. Default is False
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_delete foo eradicate=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
try:
array.destroy_volume(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def volume_eradicate(name):
'''
Eradicate a deleted volume on a Pure Storage FlashArray.
Will return False is volume is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of volume
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_eradicate foo
'''
array = _get_system()
if _get_deleted_volume(name, array) is not None:
try:
array.eradicate_volume(name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_extend(name, size):
'''
Extend an existing volume on a Pure Storage FlashArray.
Will return False if new size is less than or equal to existing size.
.. versionadded:: 2018.3.0
name : string
name of volume
size : string
New capacity of volume.
Refer to Pure Storage documentation for formatting rules.
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_extend foo 10T
'''
array = _get_system()
vol = _get_volume(name, array)
if vol is not None:
if __utils__['stringutils.human_to_bytes'](size) > vol['size']:
try:
array.extend_volume(name, size)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def snap_volume_create(name, target, overwrite=False):
'''
Create R/W volume from snapshot on a Pure Storage FlashArray.
Will return False if target volume already exists and
overwrite is not specified, or selected snapshot doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of volume snapshot
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.snap_volume_create foo.bar clone overwrite=True
'''
array = _get_system()
source, suffix = name.split('.')
if _get_snapshot(source, suffix, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_clone(name, target, overwrite=False):
'''
Clone an existing volume on a Pure Storage FlashArray.
Will return False if source volume doesn't exist, or
target volume already exists and overwrite not specified.
.. versionadded:: 2018.3.0
name : string
name of volume
target : string
name of clone volume
overwrite : boolean
overwrite clone if already exists (default: False)
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_clone foo bar overwrite=True
'''
array = _get_system()
if _get_volume(name, array) is not None:
if _get_volume(target, array) is None:
try:
array.copy_volume(name, target)
return True
except purestorage.PureError:
return False
else:
if overwrite:
try:
array.copy_volume(name, target, overwrite=overwrite)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
def volume_attach(name, host):
'''
Attach a volume to a host on a Pure Storage FlashArray.
Host and volume must exist or else will return False.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_attach foo bar
'''
array = _get_system()
if _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.connect_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
def volume_detach(name, host):
'''
Detach a volume from a host on a Pure Storage FlashArray.
Will return False if either host or volume do not exist, or
if selected volume isn't already connected to the host.
.. versionadded:: 2018.3.0
name : string
name of volume
host : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.volume_detach foo bar
'''
array = _get_system()
if _get_volume(name, array) is None or _get_host(host, array) is None:
return False
elif _get_volume(name, array) is not None and _get_host(host, array) is not None:
try:
array.disconnect_host(host, name)
return True
except purestorage.PureError:
return False
def host_create(name, iqn=None, wwn=None, nqn=None):
'''
Add a host on a Pure Storage FlashArray.
Will return False if host already exists, or the iSCSI or
Fibre Channel parameters are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host (truncated to 63 characters)
iqn : string
iSCSI IQN of host
nqn : string
NVMeF NQN of host
wwn : string
Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_create foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_host(name, array) is None:
try:
array.create_host(name)
except purestorage.PureError:
return False
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
array.delete_host(name)
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
array.delete_host(name)
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
array.delete_host(name)
return False
else:
return False
return True
def host_update(name, iqn=None, wwn=None, nqn=None):
'''
Update a hosts port definitions on a Pure Storage FlashArray.
Will return False if new port definitions are already in use
by another host, or are not in a valid format.
See Pure Storage FlashArray documentation.
.. versionadded:: 2018.3.0
name : string
name of host
nqn : string
Additional NVMeF NQN of host
iqn : string
Additional iSCSI IQN of host
wwn : string
Additional Fibre Channel WWN of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_update foo iqn='<Valid iSCSI IQN>' wwn='<Valid WWN>' nqn='<Valid NQN>'
'''
array = _get_system()
if _get_host(name, array) is not None:
if nqn is not None:
try:
array.set_host(name, addnqnlist=[nqn])
except purestorage.PureError:
return False
if iqn is not None:
try:
array.set_host(name, addiqnlist=[iqn])
except purestorage.PureError:
return False
if wwn is not None:
try:
array.set_host(name, addwwnlist=[wwn])
except purestorage.PureError:
return False
return True
else:
return False
def host_delete(name):
'''
Delete a host on a Pure Storage FlashArray (detaches all volumes).
Will return False if the host doesn't exist.
.. versionadded:: 2018.3.0
name : string
name of host
CLI Example:
.. code-block:: bash
salt '*' purefa.host_delete foo
'''
array = _get_system()
if _get_host(name, array) is not None:
for vol in array.list_host_connections(name):
try:
array.disconnect_host(name, vol['vol'])
except purestorage.PureError:
return False
try:
array.delete_host(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_create(name, host=None, volume=None):
'''
Create a hostgroup on a Pure Storage FlashArray.
Will return False if hostgroup already exists, or if
named host or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup (truncated to 63 characters)
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_create foo host=bar volume=vol
'''
array = _get_system()
if len(name) > 63:
name = name[0:63]
if _get_hgroup(name, array) is None:
try:
array.create_hgroup(name)
except purestorage.PureError:
return False
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
hg_delete(name)
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
hg_delete(name)
return False
else:
hg_delete(name)
return False
return True
else:
return False
def hg_update(name, host=None, volume=None):
'''
Adds entries to a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup doesn't exist, or host
or volume do not exist.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
host : string
name of host to add to hostgroup
volume : string
name of volume to add to hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_update foo host=bar volume=vol
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if host is not None:
if _get_host(host, array):
try:
array.set_hgroup(name, addhostlist=[host])
except purestorage.PureError:
return False
else:
return False
if volume is not None:
if _get_volume(volume, array):
try:
array.connect_hgroup(name, volume)
except purestorage.PureError:
return False
else:
return False
return True
else:
return False
def hg_delete(name):
'''
Delete a hostgroup on a Pure Storage FlashArray (removes all volumes and hosts).
Will return False is hostgroup is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_delete foo
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
for vol in array.list_hgroup_connections(name):
try:
array.disconnect_hgroup(name, vol['vol'])
except purestorage.PureError:
return False
host = array.get_hgroup(name)
try:
array.set_hgroup(name, remhostlist=host['hosts'])
array.delete_hgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def hg_remove(name, volume=None, host=None):
'''
Remove a host and/or volume from a hostgroup on a Pure Storage FlashArray.
Will return False is hostgroup does not exist, or named host or volume are
not in the hostgroup.
.. versionadded:: 2018.3.0
name : string
name of hostgroup
volume : string
name of volume to remove from hostgroup
host : string
name of host to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.hg_remove foo volume=test host=bar
'''
array = _get_system()
if _get_hgroup(name, array) is not None:
if volume is not None:
if _get_volume(volume, array):
for temp in array.list_hgroup_connections(name):
if temp['vol'] == volume:
try:
array.disconnect_hgroup(name, volume)
return True
except purestorage.PureError:
return False
return False
else:
return False
if host is not None:
if _get_host(host, array):
temp = _get_host(host, array)
if temp['hgroup'] == name:
try:
array.set_hgroup(name, remhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
if host is None and volume is None:
return False
else:
return False
def pg_create(name, hostgroup=None, host=None, volume=None, enabled=True):
'''
Create a protection group on a Pure Storage FlashArray.
Will return False is the following cases:
* Protection Grop already exists
* Protection Group in a deleted state
* More than one type is specified - protection groups are for only
hostgroups, hosts or volumes
* Named type for protection group does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_create foo [hostgroup=foo | host=bar | volume=vol] enabled=[true | false]
'''
array = _get_system()
if hostgroup is None and host is None and volume is None:
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
return False
elif __utils__['value.xor'](hostgroup, host, volume):
if _get_pgroup(name, array) is None:
try:
array.create_pgroup(name)
except purestorage.PureError:
return False
try:
array.set_pgroup(name, snap_enabled=enabled)
except purestorage.PureError:
pg_delete(name)
return False
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
pg_delete(name)
return False
else:
pg_delete(name)
return False
else:
return False
else:
return False
def pg_update(name, hostgroup=None, host=None, volume=None):
'''
Update a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Incorrect type selected for current protection group type
* Specified type does not exist
.. versionadded:: 2018.3.0
name : string
name of protection group
hostgroup : string
name of hostgroup to add to protection group
host : string
name of host to add to protection group
volume : string
name of volume to add to protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_update foo [hostgroup=foo | host=bar | volume=vol]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.add_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.add_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.add_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
if pgroup['hgroups'] is None and pgroup['hosts'] is None and pgroup['volumes'] is None:
if hostgroup is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.set_pgroup(name, addhgrouplist=[hostgroup])
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None:
if _get_host(host, array) is not None:
try:
array.set_pgroup(name, addhostlist=[host])
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None:
if _get_volume(volume, array) is not None:
try:
array.set_pgroup(name, addvollist=[volume])
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
def pg_delete(name, eradicate=False):
'''
Delete a protecton group on a Pure Storage FlashArray.
Will return False if protection group is already in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_delete foo
'''
array = _get_system()
if _get_pgroup(name, array) is not None:
try:
array.destroy_pgroup(name)
except purestorage.PureError:
return False
if eradicate is True:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return True
else:
return False
def pg_eradicate(name):
'''
Eradicate a deleted protecton group on a Pure Storage FlashArray.
Will return False if protection group is not in a deleted state.
.. versionadded:: 2018.3.0
name : string
name of protection group
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_eradicate foo
'''
array = _get_system()
if _get_deleted_pgroup(name, array) is not None:
try:
array.eradicate_pgroup(name)
return True
except purestorage.PureError:
return False
else:
return False
def pg_remove(name, hostgroup=None, host=None, volume=None):
'''
Remove a hostgroup, host or volume from a protection group on a Pure Storage FlashArray.
Will return False in the following cases:
* Protection group does not exist
* Specified type is not currently associated with the protection group
.. versionadded:: 2018.3.0
name : string
name of hostgroup
hostgroup : string
name of hostgroup to remove from protection group
host : string
name of host to remove from hostgroup
volume : string
name of volume to remove from hostgroup
CLI Example:
.. code-block:: bash
salt '*' purefa.pg_remove foo [hostgroup=bar | host=test | volume=bar]
'''
array = _get_system()
pgroup = _get_pgroup(name, array)
if pgroup is not None:
if hostgroup is not None and pgroup['hgroups'] is not None:
if _get_hgroup(hostgroup, array) is not None:
try:
array.remove_hgroup(hostgroup, name)
return True
except purestorage.PureError:
return False
else:
return False
elif host is not None and pgroup['hosts'] is not None:
if _get_host(host, array) is not None:
try:
array.remove_host(host, name)
return True
except purestorage.PureError:
return False
else:
return False
elif volume is not None and pgroup['volumes'] is not None:
if _get_volume(volume, array) is not None:
try:
array.remove_volume(volume, name)
return True
except purestorage.PureError:
return False
else:
return False
else:
return False
else:
return False
|
saltstack/salt
|
salt/states/boto_sns.py
|
present
|
python
|
def present(
name,
subscriptions=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the SNS topic exists.
name
Name of the SNS topic.
subscriptions
List of SNS subscriptions.
Each subscription is a dictionary with a protocol and endpoint key:
.. code-block:: python
[
{'protocol': 'https', 'endpoint': 'https://www.example.com/sns-endpoint'},
{'protocol': 'sqs', 'endpoint': 'arn:aws:sqs:us-west-2:123456789012:MyQueue'}
]
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
is_present = __salt__['boto_sns.exists'](
name, region=region, key=key, keyid=keyid, profile=profile
)
if is_present:
ret['result'] = True
ret['comment'] = 'AWS SNS topic {0} present.'.format(name)
else:
if __opts__['test']:
msg = 'AWS SNS topic {0} is set to be created.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
created = __salt__['boto_sns.create'](
name, region=region, key=key, keyid=keyid, profile=profile
)
if created:
msg = 'AWS SNS topic {0} created.'.format(name)
ret['comment'] = msg
ret['changes']['old'] = None
ret['changes']['new'] = {'topic': name, 'subscriptions': []}
ret['result'] = True
else:
ret['comment'] = 'Failed to create {0} AWS SNS topic'.format(name)
ret['result'] = False
return ret
if not subscriptions:
return ret
# Get current subscriptions
_subscriptions = __salt__['boto_sns.get_all_subscriptions_by_topic'](
name, region=region, key=key, keyid=keyid, profile=profile
)
# Convert subscriptions into a data strucure we can compare against
_subscriptions = [
{'protocol': s['Protocol'], 'endpoint': s['Endpoint']}
for s in _subscriptions
]
for subscription in subscriptions:
# If the subscription contains inline digest auth, AWS will *** the
# password. So we need to do the same with ours if the regex matches
# Example: https://user:****@my.endpoiint.com/foo/bar
_endpoint = subscription['endpoint']
matches = re.search(
r'https://(?P<user>\w+):(?P<pass>\w+)@',
_endpoint)
# We are using https and have auth creds - the password will be starred out,
# so star out our password so we can still match it
if matches is not None:
subscription['endpoint'] = _endpoint.replace(
matches.groupdict()['pass'],
'****')
if subscription not in _subscriptions:
# Ensure the endpoint is set back to it's original value,
# incase we starred out a password
subscription['endpoint'] = _endpoint
if __opts__['test']:
msg = ' AWS SNS subscription {0}:{1} to be set on topic {2}.'\
.format(
subscription['protocol'],
subscription['endpoint'],
name)
ret['comment'] += msg
ret['result'] = None
continue
created = __salt__['boto_sns.subscribe'](
name, subscription['protocol'], subscription['endpoint'],
region=region, key=key, keyid=keyid, profile=profile)
if created:
msg = ' AWS SNS subscription {0}:{1} set on topic {2}.'\
.format(subscription['protocol'],
subscription['endpoint'],
name)
ret['comment'] += msg
ret['changes'].setdefault('old', None)
ret['changes']\
.setdefault('new', {})\
.setdefault('subscriptions', [])\
.append(subscription)
ret['result'] = True
else:
ret['result'] = False
return ret
else:
msg = ' AWS SNS subscription {0}:{1} already set on topic {2}.'\
.format(
subscription['protocol'],
subscription['endpoint'],
name)
ret['comment'] += msg
return ret
|
Ensure the SNS topic exists.
name
Name of the SNS topic.
subscriptions
List of SNS subscriptions.
Each subscription is a dictionary with a protocol and endpoint key:
.. code-block:: python
[
{'protocol': 'https', 'endpoint': 'https://www.example.com/sns-endpoint'},
{'protocol': 'sqs', 'endpoint': 'arn:aws:sqs:us-west-2:123456789012:MyQueue'}
]
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_sns.py#L70-L207
| null |
# -*- coding: utf-8 -*-
'''
Manage SNS Topics
Create and destroy SNS topics. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
sns.keyid: GKTADJGHEIQSXMKKRBJ08H
sns.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
mytopic:
boto_sns.present:
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
mytopic:
boto_sns.present:
- region: us-east-1
- profile: mysnsprofile
# Passing in a profile
mytopic:
boto_sns.present:
- region: us-east-1
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
'''
from __future__ import absolute_import, print_function, unicode_literals
# Standard Libs
import re
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_sns' if 'boto_sns.exists' in __salt__ else False
def absent(
name,
region=None,
key=None,
keyid=None,
profile=None,
unsubscribe=False):
'''
Ensure the named sns topic is deleted.
name
Name of the SNS topic.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
unsubscribe
If True, unsubscribe all subcriptions to the SNS topic before
deleting the SNS topic
.. versionadded:: 2016.11.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_present = __salt__['boto_sns.exists'](
name, region=region, key=key, keyid=keyid, profile=profile
)
if is_present:
subscriptions = __salt__['boto_sns.get_all_subscriptions_by_topic'](
name, region=region, key=key, keyid=keyid, profile=profile
) if unsubscribe else []
failed_unsubscribe_subscriptions = []
if __opts__.get('test'):
ret['comment'] = (
'AWS SNS topic {0} is set to be removed. '
'{1} subscription(s) will be removed.'.format(name, len(subscriptions))
)
ret['result'] = None
return ret
for subscription in subscriptions:
unsubscribed = __salt__['boto_sns.unsubscribe'](
name, subscription['SubscriptionArn'], region=region,
key=key, keyid=keyid, profile=profile
)
if unsubscribed is False:
failed_unsubscribe_subscriptions.append(subscription)
deleted = __salt__['boto_sns.delete'](
name, region=region, key=key, keyid=keyid, profile=profile)
if deleted:
ret['comment'] = 'AWS SNS topic {0} deleted.'.format(name)
ret['changes']['new'] = None
if unsubscribe is False:
ret['changes']['old'] = {'topic': name}
else:
ret['changes']['old'] = {'topic': name, 'subscriptions': subscriptions}
if failed_unsubscribe_subscriptions:
ret['changes']['new'] = {'subscriptions': failed_unsubscribe_subscriptions}
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} AWS SNS topic.'.format(name)
else:
ret['comment'] = 'AWS SNS topic {0} does not exist.'.format(name)
return ret
|
saltstack/salt
|
salt/states/boto_sns.py
|
absent
|
python
|
def absent(
name,
region=None,
key=None,
keyid=None,
profile=None,
unsubscribe=False):
'''
Ensure the named sns topic is deleted.
name
Name of the SNS topic.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
unsubscribe
If True, unsubscribe all subcriptions to the SNS topic before
deleting the SNS topic
.. versionadded:: 2016.11.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_present = __salt__['boto_sns.exists'](
name, region=region, key=key, keyid=keyid, profile=profile
)
if is_present:
subscriptions = __salt__['boto_sns.get_all_subscriptions_by_topic'](
name, region=region, key=key, keyid=keyid, profile=profile
) if unsubscribe else []
failed_unsubscribe_subscriptions = []
if __opts__.get('test'):
ret['comment'] = (
'AWS SNS topic {0} is set to be removed. '
'{1} subscription(s) will be removed.'.format(name, len(subscriptions))
)
ret['result'] = None
return ret
for subscription in subscriptions:
unsubscribed = __salt__['boto_sns.unsubscribe'](
name, subscription['SubscriptionArn'], region=region,
key=key, keyid=keyid, profile=profile
)
if unsubscribed is False:
failed_unsubscribe_subscriptions.append(subscription)
deleted = __salt__['boto_sns.delete'](
name, region=region, key=key, keyid=keyid, profile=profile)
if deleted:
ret['comment'] = 'AWS SNS topic {0} deleted.'.format(name)
ret['changes']['new'] = None
if unsubscribe is False:
ret['changes']['old'] = {'topic': name}
else:
ret['changes']['old'] = {'topic': name, 'subscriptions': subscriptions}
if failed_unsubscribe_subscriptions:
ret['changes']['new'] = {'subscriptions': failed_unsubscribe_subscriptions}
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} AWS SNS topic.'.format(name)
else:
ret['comment'] = 'AWS SNS topic {0} does not exist.'.format(name)
return ret
|
Ensure the named sns topic is deleted.
name
Name of the SNS topic.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
unsubscribe
If True, unsubscribe all subcriptions to the SNS topic before
deleting the SNS topic
.. versionadded:: 2016.11.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_sns.py#L210-L287
| null |
# -*- coding: utf-8 -*-
'''
Manage SNS Topics
Create and destroy SNS topics. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
sns.keyid: GKTADJGHEIQSXMKKRBJ08H
sns.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
mytopic:
boto_sns.present:
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
mytopic:
boto_sns.present:
- region: us-east-1
- profile: mysnsprofile
# Passing in a profile
mytopic:
boto_sns.present:
- region: us-east-1
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
'''
from __future__ import absolute_import, print_function, unicode_literals
# Standard Libs
import re
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_sns' if 'boto_sns.exists' in __salt__ else False
def present(
name,
subscriptions=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the SNS topic exists.
name
Name of the SNS topic.
subscriptions
List of SNS subscriptions.
Each subscription is a dictionary with a protocol and endpoint key:
.. code-block:: python
[
{'protocol': 'https', 'endpoint': 'https://www.example.com/sns-endpoint'},
{'protocol': 'sqs', 'endpoint': 'arn:aws:sqs:us-west-2:123456789012:MyQueue'}
]
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
is_present = __salt__['boto_sns.exists'](
name, region=region, key=key, keyid=keyid, profile=profile
)
if is_present:
ret['result'] = True
ret['comment'] = 'AWS SNS topic {0} present.'.format(name)
else:
if __opts__['test']:
msg = 'AWS SNS topic {0} is set to be created.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
created = __salt__['boto_sns.create'](
name, region=region, key=key, keyid=keyid, profile=profile
)
if created:
msg = 'AWS SNS topic {0} created.'.format(name)
ret['comment'] = msg
ret['changes']['old'] = None
ret['changes']['new'] = {'topic': name, 'subscriptions': []}
ret['result'] = True
else:
ret['comment'] = 'Failed to create {0} AWS SNS topic'.format(name)
ret['result'] = False
return ret
if not subscriptions:
return ret
# Get current subscriptions
_subscriptions = __salt__['boto_sns.get_all_subscriptions_by_topic'](
name, region=region, key=key, keyid=keyid, profile=profile
)
# Convert subscriptions into a data strucure we can compare against
_subscriptions = [
{'protocol': s['Protocol'], 'endpoint': s['Endpoint']}
for s in _subscriptions
]
for subscription in subscriptions:
# If the subscription contains inline digest auth, AWS will *** the
# password. So we need to do the same with ours if the regex matches
# Example: https://user:****@my.endpoiint.com/foo/bar
_endpoint = subscription['endpoint']
matches = re.search(
r'https://(?P<user>\w+):(?P<pass>\w+)@',
_endpoint)
# We are using https and have auth creds - the password will be starred out,
# so star out our password so we can still match it
if matches is not None:
subscription['endpoint'] = _endpoint.replace(
matches.groupdict()['pass'],
'****')
if subscription not in _subscriptions:
# Ensure the endpoint is set back to it's original value,
# incase we starred out a password
subscription['endpoint'] = _endpoint
if __opts__['test']:
msg = ' AWS SNS subscription {0}:{1} to be set on topic {2}.'\
.format(
subscription['protocol'],
subscription['endpoint'],
name)
ret['comment'] += msg
ret['result'] = None
continue
created = __salt__['boto_sns.subscribe'](
name, subscription['protocol'], subscription['endpoint'],
region=region, key=key, keyid=keyid, profile=profile)
if created:
msg = ' AWS SNS subscription {0}:{1} set on topic {2}.'\
.format(subscription['protocol'],
subscription['endpoint'],
name)
ret['comment'] += msg
ret['changes'].setdefault('old', None)
ret['changes']\
.setdefault('new', {})\
.setdefault('subscriptions', [])\
.append(subscription)
ret['result'] = True
else:
ret['result'] = False
return ret
else:
msg = ' AWS SNS subscription {0}:{1} already set on topic {2}.'\
.format(
subscription['protocol'],
subscription['endpoint'],
name)
ret['comment'] += msg
return ret
|
saltstack/salt
|
salt/cloud/clouds/softlayer_hw.py
|
avail_locations
|
python
|
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
locations = conn.getLocations(id=50)
for location in locations:
ret[location['id']] = {
'id': location['id'],
'name': location['name'],
'location': location['longName'],
}
available = conn.getAvailableLocations(id=50)
for location in available:
if location.get('isAvailable', 0) is 0:
continue
ret[location['locationId']]['available'] = True
return ret
|
List all available locations
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L117-L144
|
[
"def get_conn(service='SoftLayer_Hardware'):\n '''\n Return a conn object for the passed VM data\n '''\n client = SoftLayer.Client(\n username=config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n ),\n api_key=config.get_cloud_config_value(\n 'apikey', get_configured_provider(), __opts__, search_global=False\n ),\n )\n return client[service]\n"
] |
# -*- coding: utf-8 -*-
'''
SoftLayer HW Cloud Module
=========================
The SoftLayer HW cloud module is used to control access to the SoftLayer
hardware cloud system
Use of this module only requires the ``apikey`` parameter. Set up the cloud
configuration at:
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/softlayer.conf``:
.. code-block:: yaml
my-softlayer-config:
# SoftLayer account api key
user: MYLOGIN
apikey: JVkbSJDGHSDKUKSDJfhsdklfjgsjdkflhjlsdfffhgdgjkenrtuinv
driver: softlayer_hw
The SoftLayer Python Library needs to be installed in order to use the
SoftLayer salt.cloud modules. See: https://pypi.python.org/pypi/SoftLayer
:depends: softlayer
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
import decimal
# Import salt cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
# Attempt to import softlayer lib
try:
import SoftLayer
HAS_SLLIBS = True
except ImportError:
HAS_SLLIBS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'softlayer_hw'
# Only load in this module if the SoftLayer configurations are in place
def __virtual__():
'''
Check for SoftLayer configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('apikey',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'softlayer': HAS_SLLIBS}
)
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def get_conn(service='SoftLayer_Hardware'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service]
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'server_core':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'os':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def get_location(vm_=None):
'''
Return the location to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
#default=DEFAULT_LOCATION,
search_global=False
)
)
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer_hw',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn(service='SoftLayer_Product_Order')
kwargs = {
'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
'quantity': 1,
'hardware': [{
'hostname': hostname,
'domain': domain,
}],
# Baremetal Package
'packageId': 50,
'prices': [
# Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
{'id': vm_['size']},
# HDD Ex: 19: 250GB SATA II
{'id': vm_['hdd']},
# Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
{'id': vm_['image']},
# The following items are currently required
# Reboot / Remote Console
{'id': '905'},
# 1 IP Address
{'id': '21'},
# Host Ping Monitoring
{'id': '55'},
# Email and Ticket Notifications
{'id': '57'},
# Automated Notification Response
{'id': '58'},
# Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': '420'},
# Nessus Vulnerability Assessment & Reporting
{'id': '418'},
],
}
optional_products = config.get_cloud_config_value(
'optional_products', vm_, __opts__, default=[]
)
for product in optional_products:
kwargs['prices'].append({'id': product})
# Default is 273 (100 Mbps Public & Private Networks)
port_speed = config.get_cloud_config_value(
'port_speed', vm_, __opts__, default=273
)
kwargs['prices'].append({'id': port_speed})
# Default is 1800 (0 GB Bandwidth)
bandwidth = config.get_cloud_config_value(
'bandwidth', vm_, __opts__, default=1800
)
kwargs['prices'].append({'id': bandwidth})
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['prices'].append({'id': post_uri})
vlan_id = config.get_cloud_config_value(
'vlan', vm_, __opts__, default=False
)
if vlan_id:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': vlan_id,
}
}
location = get_location(vm_)
if location:
kwargs['location'] = location
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.placeOrder(kwargs)
# Leaving the following line in, commented, for easy debugging
#response = conn.verifyOrder(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if 'primaryIpAddress' in nodes[hostname]:
return nodes[hostname]['primaryIpAddress']
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
ssh_connect_timeout = config.get_cloud_config_value(
# 15 minutes
'ssh_connect_timeout', vm_, __opts__, 900
)
if not salt.utils.cloud.wait_for_port(ip_address,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_passwd():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] \
and 'passwords' in node['operatingSystem'] \
and node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
passwd = salt.utils.cloud.wait_for_fun(
get_passwd,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default='root'
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getHardware(mask=mask)
for node in response:
ret[node['hostname']] = node
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['memoryCount'],
'cpus': nodes[node]['processorPhysicalCoreAmount'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from SoftLayer concerning a guest
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn(service='SoftLayer_Ticket')
response = conn.createCancelServerTicket(
{
'id': node['id'],
'reason': 'Salt Cloud Hardware Server Cancellation',
'content': 'Please cancel this server',
'cancelAssociatedItems': True,
'attachmentType': 'HARDWARE',
}
)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response
def list_vlans(call=None):
'''
List all VLANs associated with the account
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Account')
return conn.getNetworkVlans()
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Softlayer HW
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'softlayer_hw':
return {'Error': 'The requested profile does not belong to Softlayer HW'}
raw = {}
ret = {}
ret['per_hour'] = 0
conn = get_conn(service='SoftLayer_Product_Item_Price')
for item in profile:
if item in ('profile', 'provider', 'location'):
continue
price = conn.getObject(id=profile[item])
raw[item] = price
ret['per_hour'] += decimal.Decimal(price.get('hourlyRecurringFee', 0))
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def show_all_prices(call=None, kwargs=None):
'''
Return a dict of all prices on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_prices function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn(service='SoftLayer_Product_Package')
if 'code' not in kwargs:
return conn.getCategories(id=50)
ret = {}
for category in conn.getCategories(id=50):
if category['categoryCode'] != kwargs['code']:
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def show_all_categories(call=None):
'''
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_categories function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Product_Package')
categories = []
for category in conn.getCategories(id=50):
categories.append(category['categoryCode'])
return {'category_codes': categories}
|
saltstack/salt
|
salt/cloud/clouds/softlayer_hw.py
|
avail_images
|
python
|
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'os':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
|
Return a dict of all available VM images on the cloud provider.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L171-L190
|
[
"def get_conn(service='SoftLayer_Hardware'):\n '''\n Return a conn object for the passed VM data\n '''\n client = SoftLayer.Client(\n username=config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n ),\n api_key=config.get_cloud_config_value(\n 'apikey', get_configured_provider(), __opts__, search_global=False\n ),\n )\n return client[service]\n"
] |
# -*- coding: utf-8 -*-
'''
SoftLayer HW Cloud Module
=========================
The SoftLayer HW cloud module is used to control access to the SoftLayer
hardware cloud system
Use of this module only requires the ``apikey`` parameter. Set up the cloud
configuration at:
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/softlayer.conf``:
.. code-block:: yaml
my-softlayer-config:
# SoftLayer account api key
user: MYLOGIN
apikey: JVkbSJDGHSDKUKSDJfhsdklfjgsjdkflhjlsdfffhgdgjkenrtuinv
driver: softlayer_hw
The SoftLayer Python Library needs to be installed in order to use the
SoftLayer salt.cloud modules. See: https://pypi.python.org/pypi/SoftLayer
:depends: softlayer
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
import decimal
# Import salt cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
# Attempt to import softlayer lib
try:
import SoftLayer
HAS_SLLIBS = True
except ImportError:
HAS_SLLIBS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'softlayer_hw'
# Only load in this module if the SoftLayer configurations are in place
def __virtual__():
'''
Check for SoftLayer configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('apikey',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'softlayer': HAS_SLLIBS}
)
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def get_conn(service='SoftLayer_Hardware'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service]
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
locations = conn.getLocations(id=50)
for location in locations:
ret[location['id']] = {
'id': location['id'],
'name': location['name'],
'location': location['longName'],
}
available = conn.getAvailableLocations(id=50)
for location in available:
if location.get('isAvailable', 0) is 0:
continue
ret[location['locationId']]['available'] = True
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'server_core':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def get_location(vm_=None):
'''
Return the location to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
#default=DEFAULT_LOCATION,
search_global=False
)
)
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer_hw',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn(service='SoftLayer_Product_Order')
kwargs = {
'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
'quantity': 1,
'hardware': [{
'hostname': hostname,
'domain': domain,
}],
# Baremetal Package
'packageId': 50,
'prices': [
# Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
{'id': vm_['size']},
# HDD Ex: 19: 250GB SATA II
{'id': vm_['hdd']},
# Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
{'id': vm_['image']},
# The following items are currently required
# Reboot / Remote Console
{'id': '905'},
# 1 IP Address
{'id': '21'},
# Host Ping Monitoring
{'id': '55'},
# Email and Ticket Notifications
{'id': '57'},
# Automated Notification Response
{'id': '58'},
# Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': '420'},
# Nessus Vulnerability Assessment & Reporting
{'id': '418'},
],
}
optional_products = config.get_cloud_config_value(
'optional_products', vm_, __opts__, default=[]
)
for product in optional_products:
kwargs['prices'].append({'id': product})
# Default is 273 (100 Mbps Public & Private Networks)
port_speed = config.get_cloud_config_value(
'port_speed', vm_, __opts__, default=273
)
kwargs['prices'].append({'id': port_speed})
# Default is 1800 (0 GB Bandwidth)
bandwidth = config.get_cloud_config_value(
'bandwidth', vm_, __opts__, default=1800
)
kwargs['prices'].append({'id': bandwidth})
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['prices'].append({'id': post_uri})
vlan_id = config.get_cloud_config_value(
'vlan', vm_, __opts__, default=False
)
if vlan_id:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': vlan_id,
}
}
location = get_location(vm_)
if location:
kwargs['location'] = location
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.placeOrder(kwargs)
# Leaving the following line in, commented, for easy debugging
#response = conn.verifyOrder(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if 'primaryIpAddress' in nodes[hostname]:
return nodes[hostname]['primaryIpAddress']
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
ssh_connect_timeout = config.get_cloud_config_value(
# 15 minutes
'ssh_connect_timeout', vm_, __opts__, 900
)
if not salt.utils.cloud.wait_for_port(ip_address,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_passwd():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] \
and 'passwords' in node['operatingSystem'] \
and node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
passwd = salt.utils.cloud.wait_for_fun(
get_passwd,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default='root'
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getHardware(mask=mask)
for node in response:
ret[node['hostname']] = node
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['memoryCount'],
'cpus': nodes[node]['processorPhysicalCoreAmount'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from SoftLayer concerning a guest
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn(service='SoftLayer_Ticket')
response = conn.createCancelServerTicket(
{
'id': node['id'],
'reason': 'Salt Cloud Hardware Server Cancellation',
'content': 'Please cancel this server',
'cancelAssociatedItems': True,
'attachmentType': 'HARDWARE',
}
)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response
def list_vlans(call=None):
'''
List all VLANs associated with the account
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Account')
return conn.getNetworkVlans()
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Softlayer HW
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'softlayer_hw':
return {'Error': 'The requested profile does not belong to Softlayer HW'}
raw = {}
ret = {}
ret['per_hour'] = 0
conn = get_conn(service='SoftLayer_Product_Item_Price')
for item in profile:
if item in ('profile', 'provider', 'location'):
continue
price = conn.getObject(id=profile[item])
raw[item] = price
ret['per_hour'] += decimal.Decimal(price.get('hourlyRecurringFee', 0))
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def show_all_prices(call=None, kwargs=None):
'''
Return a dict of all prices on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_prices function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn(service='SoftLayer_Product_Package')
if 'code' not in kwargs:
return conn.getCategories(id=50)
ret = {}
for category in conn.getCategories(id=50):
if category['categoryCode'] != kwargs['code']:
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def show_all_categories(call=None):
'''
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_categories function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Product_Package')
categories = []
for category in conn.getCategories(id=50):
categories.append(category['categoryCode'])
return {'category_codes': categories}
|
saltstack/salt
|
salt/cloud/clouds/softlayer_hw.py
|
create
|
python
|
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer_hw',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn(service='SoftLayer_Product_Order')
kwargs = {
'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
'quantity': 1,
'hardware': [{
'hostname': hostname,
'domain': domain,
}],
# Baremetal Package
'packageId': 50,
'prices': [
# Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
{'id': vm_['size']},
# HDD Ex: 19: 250GB SATA II
{'id': vm_['hdd']},
# Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
{'id': vm_['image']},
# The following items are currently required
# Reboot / Remote Console
{'id': '905'},
# 1 IP Address
{'id': '21'},
# Host Ping Monitoring
{'id': '55'},
# Email and Ticket Notifications
{'id': '57'},
# Automated Notification Response
{'id': '58'},
# Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': '420'},
# Nessus Vulnerability Assessment & Reporting
{'id': '418'},
],
}
optional_products = config.get_cloud_config_value(
'optional_products', vm_, __opts__, default=[]
)
for product in optional_products:
kwargs['prices'].append({'id': product})
# Default is 273 (100 Mbps Public & Private Networks)
port_speed = config.get_cloud_config_value(
'port_speed', vm_, __opts__, default=273
)
kwargs['prices'].append({'id': port_speed})
# Default is 1800 (0 GB Bandwidth)
bandwidth = config.get_cloud_config_value(
'bandwidth', vm_, __opts__, default=1800
)
kwargs['prices'].append({'id': bandwidth})
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['prices'].append({'id': post_uri})
vlan_id = config.get_cloud_config_value(
'vlan', vm_, __opts__, default=False
)
if vlan_id:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': vlan_id,
}
}
location = get_location(vm_)
if location:
kwargs['location'] = location
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.placeOrder(kwargs)
# Leaving the following line in, commented, for easy debugging
#response = conn.verifyOrder(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if 'primaryIpAddress' in nodes[hostname]:
return nodes[hostname]['primaryIpAddress']
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
ssh_connect_timeout = config.get_cloud_config_value(
# 15 minutes
'ssh_connect_timeout', vm_, __opts__, 900
)
if not salt.utils.cloud.wait_for_port(ip_address,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_passwd():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] \
and 'passwords' in node['operatingSystem'] \
and node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
passwd = salt.utils.cloud.wait_for_fun(
get_passwd,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default='root'
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
|
Create a single VM from a data dict
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L212-L425
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def is_profile_configured(opts, provider, profile_name, vm_=None):\n '''\n Check if the requested profile contains the minimum required parameters for\n a profile.\n\n Required parameters include image and provider for all drivers, while some\n drivers also require size keys.\n\n .. versionadded:: 2015.8.0\n '''\n # Standard dict keys required by all drivers.\n required_keys = ['provider']\n alias, driver = provider.split(':')\n\n # Most drivers need an image to be specified, but some do not.\n non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']\n\n # Most drivers need a size, but some do not.\n non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',\n 'softlayer', 'softlayer_hw', 'vmware', 'vsphere',\n 'virtualbox', 'libvirt', 'oneandone', 'profitbricks']\n\n provider_key = opts['providers'][alias][driver]\n profile_key = opts['providers'][alias][driver]['profiles'][profile_name]\n\n # If cloning on Linode, size and image are not necessary.\n # They are obtained from the to-be-cloned VM.\n if driver == 'linode' and profile_key.get('clonefrom', False):\n non_image_drivers.append('linode')\n non_size_drivers.append('linode')\n elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):\n non_image_drivers.append('gce')\n\n # If cloning on VMware, specifying image is not necessary.\n if driver == 'vmware' and 'image' not in list(profile_key.keys()):\n non_image_drivers.append('vmware')\n\n if driver not in non_image_drivers:\n required_keys.append('image')\n if driver == 'vmware':\n required_keys.append('datastore')\n elif driver in ['linode', 'virtualbox']:\n required_keys.append('clonefrom')\n elif driver == 'nova':\n nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']\n if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):\n required_keys.extend(nova_image_keys)\n\n if driver not in non_size_drivers:\n required_keys.append('size')\n\n # Check if required fields are supplied in the provider config. If they\n # are present, remove it from the required_keys list.\n for item in list(required_keys):\n if item in provider_key:\n required_keys.remove(item)\n\n # If a vm_ dict was passed in, use that information to get any other configs\n # that we might have missed thus far, such as a option provided in a map file.\n if vm_:\n for item in list(required_keys):\n if item in vm_:\n required_keys.remove(item)\n\n # Check for remaining required parameters in the profile config.\n for item in required_keys:\n if profile_key.get(item, None) is None:\n # There's at least one required configuration item which is not set.\n log.error(\n \"The required '%s' configuration setting is missing from \"\n \"the '%s' profile, which is configured under the '%s' alias.\",\n item, profile_name, alias\n )\n return False\n\n return True\n",
"def get_location(vm_=None):\n '''\n Return the location to use, in this order:\n - CLI parameter\n - VM parameter\n - Cloud profile setting\n '''\n return __opts__.get(\n 'location',\n config.get_cloud_config_value(\n 'location',\n vm_ or get_configured_provider(),\n __opts__,\n #default=DEFAULT_LOCATION,\n search_global=False\n )\n )\n",
"def get_conn(service='SoftLayer_Hardware'):\n '''\n Return a conn object for the passed VM data\n '''\n client = SoftLayer.Client(\n username=config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n ),\n api_key=config.get_cloud_config_value(\n 'apikey', get_configured_provider(), __opts__, search_global=False\n ),\n )\n return client[service]\n",
"def wait_for_fun(fun, timeout=900, **kwargs):\n '''\n Wait until a function finishes, or times out\n '''\n start = time.time()\n log.debug('Attempting function %s', fun)\n trycount = 0\n while True:\n trycount += 1\n try:\n response = fun(**kwargs)\n if not isinstance(response, bool):\n return response\n except Exception as exc:\n log.debug('Caught exception in wait_for_fun: %s', exc)\n time.sleep(1)\n log.debug('Retrying function %s on (try %s)', fun, trycount)\n if time.time() - start > timeout:\n log.error('Function timed out: %s', timeout)\n return False\n",
"def wait_for_port(host, port=22, timeout=900, gateway=None):\n '''\n Wait until a connection to the specified port can be made on a specified\n host. This is usually port 22 (for SSH), but in the case of Windows\n installations, it might be port 445 (for psexec). It may also be an\n alternate port for SSH, depending on the base image.\n '''\n start = time.time()\n # Assign test ports because if a gateway is defined\n # we first want to test the gateway before the host.\n test_ssh_host = host\n test_ssh_port = port\n\n if gateway:\n ssh_gateway = gateway['ssh_gateway']\n ssh_gateway_port = 22\n if ':' in ssh_gateway:\n ssh_gateway, ssh_gateway_port = ssh_gateway.split(':')\n if 'ssh_gateway_port' in gateway:\n ssh_gateway_port = gateway['ssh_gateway_port']\n test_ssh_host = ssh_gateway\n test_ssh_port = ssh_gateway_port\n log.debug(\n 'Attempting connection to host %s on port %s '\n 'via gateway %s on port %s',\n host, port, ssh_gateway, ssh_gateway_port\n )\n else:\n log.debug('Attempting connection to host %s on port %s', host, port)\n trycount = 0\n while True:\n trycount += 1\n try:\n if socket.inet_pton(socket.AF_INET6, host):\n sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n else:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n except socket.error:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n sock.settimeout(5)\n sock.connect((test_ssh_host, int(test_ssh_port)))\n # Stop any remaining reads/writes on the socket\n sock.shutdown(socket.SHUT_RDWR)\n # Close it!\n sock.close()\n break\n except socket.error as exc:\n log.debug('Caught exception in wait_for_port: %s', exc)\n time.sleep(1)\n if time.time() - start > timeout:\n log.error('Port connection timed out: %s', timeout)\n return False\n log.debug(\n 'Retrying connection to %s %s on port %s (try %s)',\n 'gateway' if gateway else 'host', test_ssh_host, test_ssh_port, trycount\n )\n if not gateway:\n return True\n # Let the user know that his gateway is good!\n log.debug('Gateway %s on port %s is reachable.', test_ssh_host, test_ssh_port)\n\n # Now we need to test the host via the gateway.\n # We will use netcat on the gateway to test the port\n ssh_args = []\n ssh_args.extend([\n # Don't add new hosts to the host key database\n '-oStrictHostKeyChecking=no',\n # Set hosts key database path to /dev/null, i.e., non-existing\n '-oUserKnownHostsFile=/dev/null',\n # Don't re-use the SSH connection. Less failures.\n '-oControlPath=none'\n ])\n # There should never be both a password and an ssh key passed in, so\n if 'ssh_gateway_key' in gateway:\n ssh_args.extend([\n # tell SSH to skip password authentication\n '-oPasswordAuthentication=no',\n '-oChallengeResponseAuthentication=no',\n # Make sure public key authentication is enabled\n '-oPubkeyAuthentication=yes',\n # do only use the provided identity file\n '-oIdentitiesOnly=yes',\n # No Keyboard interaction!\n '-oKbdInteractiveAuthentication=no',\n # Also, specify the location of the key file\n '-i {0}'.format(gateway['ssh_gateway_key'])\n ])\n # Netcat command testing remote port\n command = 'nc -z -w5 -q0 {0} {1}'.format(host, port)\n # SSH command\n pcmd = 'ssh {0} {1}@{2} -p {3} {4}'.format(\n ' '.join(ssh_args), gateway['ssh_gateway_user'], ssh_gateway,\n ssh_gateway_port, pipes.quote('date')\n )\n cmd = 'ssh {0} {1}@{2} -p {3} {4}'.format(\n ' '.join(ssh_args), gateway['ssh_gateway_user'], ssh_gateway,\n ssh_gateway_port, pipes.quote(command)\n )\n log.debug('SSH command: \\'%s\\'', cmd)\n\n kwargs = {'display_ssh_output': False,\n 'password': gateway.get('ssh_gateway_password', None)}\n trycount = 0\n usable_gateway = False\n gateway_retries = 5\n while True:\n trycount += 1\n # test gateway usage\n if not usable_gateway:\n pstatus = _exec_ssh_cmd(pcmd, allow_failure=True, **kwargs)\n if pstatus == 0:\n usable_gateway = True\n else:\n gateway_retries -= 1\n log.error(\n 'Gateway usage seems to be broken, '\n 'password error ? Tries left: %s', gateway_retries)\n if not gateway_retries:\n raise SaltCloudExecutionFailure(\n 'SSH gateway is reachable but we can not login')\n # then try to reach out the target\n if usable_gateway:\n status = _exec_ssh_cmd(cmd, allow_failure=True, **kwargs)\n # Get the exit code of the SSH command.\n # If 0 then the port is open.\n if status == 0:\n return True\n time.sleep(1)\n if time.time() - start > timeout:\n log.error('Port connection timed out: %s', timeout)\n return False\n log.debug(\n 'Retrying connection to host %s on port %s '\n 'via gateway %s on port %s. (try %s)',\n host, port, ssh_gateway, ssh_gateway_port, trycount\n )\n"
] |
# -*- coding: utf-8 -*-
'''
SoftLayer HW Cloud Module
=========================
The SoftLayer HW cloud module is used to control access to the SoftLayer
hardware cloud system
Use of this module only requires the ``apikey`` parameter. Set up the cloud
configuration at:
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/softlayer.conf``:
.. code-block:: yaml
my-softlayer-config:
# SoftLayer account api key
user: MYLOGIN
apikey: JVkbSJDGHSDKUKSDJfhsdklfjgsjdkflhjlsdfffhgdgjkenrtuinv
driver: softlayer_hw
The SoftLayer Python Library needs to be installed in order to use the
SoftLayer salt.cloud modules. See: https://pypi.python.org/pypi/SoftLayer
:depends: softlayer
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
import decimal
# Import salt cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
# Attempt to import softlayer lib
try:
import SoftLayer
HAS_SLLIBS = True
except ImportError:
HAS_SLLIBS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'softlayer_hw'
# Only load in this module if the SoftLayer configurations are in place
def __virtual__():
'''
Check for SoftLayer configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('apikey',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'softlayer': HAS_SLLIBS}
)
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def get_conn(service='SoftLayer_Hardware'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service]
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
locations = conn.getLocations(id=50)
for location in locations:
ret[location['id']] = {
'id': location['id'],
'name': location['name'],
'location': location['longName'],
}
available = conn.getAvailableLocations(id=50)
for location in available:
if location.get('isAvailable', 0) is 0:
continue
ret[location['locationId']]['available'] = True
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'server_core':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'os':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def get_location(vm_=None):
'''
Return the location to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
#default=DEFAULT_LOCATION,
search_global=False
)
)
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getHardware(mask=mask)
for node in response:
ret[node['hostname']] = node
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['memoryCount'],
'cpus': nodes[node]['processorPhysicalCoreAmount'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from SoftLayer concerning a guest
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn(service='SoftLayer_Ticket')
response = conn.createCancelServerTicket(
{
'id': node['id'],
'reason': 'Salt Cloud Hardware Server Cancellation',
'content': 'Please cancel this server',
'cancelAssociatedItems': True,
'attachmentType': 'HARDWARE',
}
)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response
def list_vlans(call=None):
'''
List all VLANs associated with the account
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Account')
return conn.getNetworkVlans()
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Softlayer HW
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'softlayer_hw':
return {'Error': 'The requested profile does not belong to Softlayer HW'}
raw = {}
ret = {}
ret['per_hour'] = 0
conn = get_conn(service='SoftLayer_Product_Item_Price')
for item in profile:
if item in ('profile', 'provider', 'location'):
continue
price = conn.getObject(id=profile[item])
raw[item] = price
ret['per_hour'] += decimal.Decimal(price.get('hourlyRecurringFee', 0))
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def show_all_prices(call=None, kwargs=None):
'''
Return a dict of all prices on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_prices function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn(service='SoftLayer_Product_Package')
if 'code' not in kwargs:
return conn.getCategories(id=50)
ret = {}
for category in conn.getCategories(id=50):
if category['categoryCode'] != kwargs['code']:
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def show_all_categories(call=None):
'''
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_categories function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Product_Package')
categories = []
for category in conn.getCategories(id=50):
categories.append(category['categoryCode'])
return {'category_codes': categories}
|
saltstack/salt
|
salt/cloud/clouds/softlayer_hw.py
|
list_nodes_full
|
python
|
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getHardware(mask=mask)
for node in response:
ret[node['hostname']] = node
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret
|
Return a list of the VMs that are on the provider
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L428-L446
|
[
"def get_conn(service='SoftLayer_Hardware'):\n '''\n Return a conn object for the passed VM data\n '''\n client = SoftLayer.Client(\n username=config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n ),\n api_key=config.get_cloud_config_value(\n 'apikey', get_configured_provider(), __opts__, search_global=False\n ),\n )\n return client[service]\n"
] |
# -*- coding: utf-8 -*-
'''
SoftLayer HW Cloud Module
=========================
The SoftLayer HW cloud module is used to control access to the SoftLayer
hardware cloud system
Use of this module only requires the ``apikey`` parameter. Set up the cloud
configuration at:
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/softlayer.conf``:
.. code-block:: yaml
my-softlayer-config:
# SoftLayer account api key
user: MYLOGIN
apikey: JVkbSJDGHSDKUKSDJfhsdklfjgsjdkflhjlsdfffhgdgjkenrtuinv
driver: softlayer_hw
The SoftLayer Python Library needs to be installed in order to use the
SoftLayer salt.cloud modules. See: https://pypi.python.org/pypi/SoftLayer
:depends: softlayer
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
import decimal
# Import salt cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
# Attempt to import softlayer lib
try:
import SoftLayer
HAS_SLLIBS = True
except ImportError:
HAS_SLLIBS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'softlayer_hw'
# Only load in this module if the SoftLayer configurations are in place
def __virtual__():
'''
Check for SoftLayer configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('apikey',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'softlayer': HAS_SLLIBS}
)
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def get_conn(service='SoftLayer_Hardware'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service]
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
locations = conn.getLocations(id=50)
for location in locations:
ret[location['id']] = {
'id': location['id'],
'name': location['name'],
'location': location['longName'],
}
available = conn.getAvailableLocations(id=50)
for location in available:
if location.get('isAvailable', 0) is 0:
continue
ret[location['locationId']]['available'] = True
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'server_core':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'os':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def get_location(vm_=None):
'''
Return the location to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
#default=DEFAULT_LOCATION,
search_global=False
)
)
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer_hw',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn(service='SoftLayer_Product_Order')
kwargs = {
'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
'quantity': 1,
'hardware': [{
'hostname': hostname,
'domain': domain,
}],
# Baremetal Package
'packageId': 50,
'prices': [
# Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
{'id': vm_['size']},
# HDD Ex: 19: 250GB SATA II
{'id': vm_['hdd']},
# Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
{'id': vm_['image']},
# The following items are currently required
# Reboot / Remote Console
{'id': '905'},
# 1 IP Address
{'id': '21'},
# Host Ping Monitoring
{'id': '55'},
# Email and Ticket Notifications
{'id': '57'},
# Automated Notification Response
{'id': '58'},
# Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': '420'},
# Nessus Vulnerability Assessment & Reporting
{'id': '418'},
],
}
optional_products = config.get_cloud_config_value(
'optional_products', vm_, __opts__, default=[]
)
for product in optional_products:
kwargs['prices'].append({'id': product})
# Default is 273 (100 Mbps Public & Private Networks)
port_speed = config.get_cloud_config_value(
'port_speed', vm_, __opts__, default=273
)
kwargs['prices'].append({'id': port_speed})
# Default is 1800 (0 GB Bandwidth)
bandwidth = config.get_cloud_config_value(
'bandwidth', vm_, __opts__, default=1800
)
kwargs['prices'].append({'id': bandwidth})
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['prices'].append({'id': post_uri})
vlan_id = config.get_cloud_config_value(
'vlan', vm_, __opts__, default=False
)
if vlan_id:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': vlan_id,
}
}
location = get_location(vm_)
if location:
kwargs['location'] = location
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.placeOrder(kwargs)
# Leaving the following line in, commented, for easy debugging
#response = conn.verifyOrder(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if 'primaryIpAddress' in nodes[hostname]:
return nodes[hostname]['primaryIpAddress']
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
ssh_connect_timeout = config.get_cloud_config_value(
# 15 minutes
'ssh_connect_timeout', vm_, __opts__, 900
)
if not salt.utils.cloud.wait_for_port(ip_address,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_passwd():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] \
and 'passwords' in node['operatingSystem'] \
and node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
passwd = salt.utils.cloud.wait_for_fun(
get_passwd,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default='root'
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['memoryCount'],
'cpus': nodes[node]['processorPhysicalCoreAmount'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from SoftLayer concerning a guest
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn(service='SoftLayer_Ticket')
response = conn.createCancelServerTicket(
{
'id': node['id'],
'reason': 'Salt Cloud Hardware Server Cancellation',
'content': 'Please cancel this server',
'cancelAssociatedItems': True,
'attachmentType': 'HARDWARE',
}
)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response
def list_vlans(call=None):
'''
List all VLANs associated with the account
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Account')
return conn.getNetworkVlans()
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Softlayer HW
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'softlayer_hw':
return {'Error': 'The requested profile does not belong to Softlayer HW'}
raw = {}
ret = {}
ret['per_hour'] = 0
conn = get_conn(service='SoftLayer_Product_Item_Price')
for item in profile:
if item in ('profile', 'provider', 'location'):
continue
price = conn.getObject(id=profile[item])
raw[item] = price
ret['per_hour'] += decimal.Decimal(price.get('hourlyRecurringFee', 0))
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def show_all_prices(call=None, kwargs=None):
'''
Return a dict of all prices on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_prices function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn(service='SoftLayer_Product_Package')
if 'code' not in kwargs:
return conn.getCategories(id=50)
ret = {}
for category in conn.getCategories(id=50):
if category['categoryCode'] != kwargs['code']:
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def show_all_categories(call=None):
'''
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_categories function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Product_Package')
categories = []
for category in conn.getCategories(id=50):
categories.append(category['categoryCode'])
return {'category_codes': categories}
|
saltstack/salt
|
salt/cloud/clouds/softlayer_hw.py
|
show_pricing
|
python
|
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Softlayer HW
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'softlayer_hw':
return {'Error': 'The requested profile does not belong to Softlayer HW'}
raw = {}
ret = {}
ret['per_hour'] = 0
conn = get_conn(service='SoftLayer_Product_Item_Price')
for item in profile:
if item in ('profile', 'provider', 'location'):
continue
price = conn.getObject(id=profile[item])
raw[item] = price
ret['per_hour'] += decimal.Decimal(price.get('hourlyRecurringFee', 0))
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
|
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L566-L616
|
[
"def get_conn(service='SoftLayer_Hardware'):\n '''\n Return a conn object for the passed VM data\n '''\n client = SoftLayer.Client(\n username=config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n ),\n api_key=config.get_cloud_config_value(\n 'apikey', get_configured_provider(), __opts__, search_global=False\n ),\n )\n return client[service]\n"
] |
# -*- coding: utf-8 -*-
'''
SoftLayer HW Cloud Module
=========================
The SoftLayer HW cloud module is used to control access to the SoftLayer
hardware cloud system
Use of this module only requires the ``apikey`` parameter. Set up the cloud
configuration at:
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/softlayer.conf``:
.. code-block:: yaml
my-softlayer-config:
# SoftLayer account api key
user: MYLOGIN
apikey: JVkbSJDGHSDKUKSDJfhsdklfjgsjdkflhjlsdfffhgdgjkenrtuinv
driver: softlayer_hw
The SoftLayer Python Library needs to be installed in order to use the
SoftLayer salt.cloud modules. See: https://pypi.python.org/pypi/SoftLayer
:depends: softlayer
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
import decimal
# Import salt cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
# Attempt to import softlayer lib
try:
import SoftLayer
HAS_SLLIBS = True
except ImportError:
HAS_SLLIBS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'softlayer_hw'
# Only load in this module if the SoftLayer configurations are in place
def __virtual__():
'''
Check for SoftLayer configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('apikey',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'softlayer': HAS_SLLIBS}
)
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def get_conn(service='SoftLayer_Hardware'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service]
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
locations = conn.getLocations(id=50)
for location in locations:
ret[location['id']] = {
'id': location['id'],
'name': location['name'],
'location': location['longName'],
}
available = conn.getAvailableLocations(id=50)
for location in available:
if location.get('isAvailable', 0) is 0:
continue
ret[location['locationId']]['available'] = True
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'server_core':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'os':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def get_location(vm_=None):
'''
Return the location to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
#default=DEFAULT_LOCATION,
search_global=False
)
)
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer_hw',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn(service='SoftLayer_Product_Order')
kwargs = {
'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
'quantity': 1,
'hardware': [{
'hostname': hostname,
'domain': domain,
}],
# Baremetal Package
'packageId': 50,
'prices': [
# Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
{'id': vm_['size']},
# HDD Ex: 19: 250GB SATA II
{'id': vm_['hdd']},
# Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
{'id': vm_['image']},
# The following items are currently required
# Reboot / Remote Console
{'id': '905'},
# 1 IP Address
{'id': '21'},
# Host Ping Monitoring
{'id': '55'},
# Email and Ticket Notifications
{'id': '57'},
# Automated Notification Response
{'id': '58'},
# Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': '420'},
# Nessus Vulnerability Assessment & Reporting
{'id': '418'},
],
}
optional_products = config.get_cloud_config_value(
'optional_products', vm_, __opts__, default=[]
)
for product in optional_products:
kwargs['prices'].append({'id': product})
# Default is 273 (100 Mbps Public & Private Networks)
port_speed = config.get_cloud_config_value(
'port_speed', vm_, __opts__, default=273
)
kwargs['prices'].append({'id': port_speed})
# Default is 1800 (0 GB Bandwidth)
bandwidth = config.get_cloud_config_value(
'bandwidth', vm_, __opts__, default=1800
)
kwargs['prices'].append({'id': bandwidth})
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['prices'].append({'id': post_uri})
vlan_id = config.get_cloud_config_value(
'vlan', vm_, __opts__, default=False
)
if vlan_id:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': vlan_id,
}
}
location = get_location(vm_)
if location:
kwargs['location'] = location
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.placeOrder(kwargs)
# Leaving the following line in, commented, for easy debugging
#response = conn.verifyOrder(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if 'primaryIpAddress' in nodes[hostname]:
return nodes[hostname]['primaryIpAddress']
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
ssh_connect_timeout = config.get_cloud_config_value(
# 15 minutes
'ssh_connect_timeout', vm_, __opts__, 900
)
if not salt.utils.cloud.wait_for_port(ip_address,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_passwd():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] \
and 'passwords' in node['operatingSystem'] \
and node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
passwd = salt.utils.cloud.wait_for_fun(
get_passwd,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default='root'
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getHardware(mask=mask)
for node in response:
ret[node['hostname']] = node
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['memoryCount'],
'cpus': nodes[node]['processorPhysicalCoreAmount'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from SoftLayer concerning a guest
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn(service='SoftLayer_Ticket')
response = conn.createCancelServerTicket(
{
'id': node['id'],
'reason': 'Salt Cloud Hardware Server Cancellation',
'content': 'Please cancel this server',
'cancelAssociatedItems': True,
'attachmentType': 'HARDWARE',
}
)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response
def list_vlans(call=None):
'''
List all VLANs associated with the account
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Account')
return conn.getNetworkVlans()
def show_all_prices(call=None, kwargs=None):
'''
Return a dict of all prices on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_prices function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn(service='SoftLayer_Product_Package')
if 'code' not in kwargs:
return conn.getCategories(id=50)
ret = {}
for category in conn.getCategories(id=50):
if category['categoryCode'] != kwargs['code']:
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def show_all_categories(call=None):
'''
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_categories function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Product_Package')
categories = []
for category in conn.getCategories(id=50):
categories.append(category['categoryCode'])
return {'category_codes': categories}
|
saltstack/salt
|
salt/cloud/clouds/softlayer_hw.py
|
show_all_prices
|
python
|
def show_all_prices(call=None, kwargs=None):
'''
Return a dict of all prices on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_prices function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn(service='SoftLayer_Product_Package')
if 'code' not in kwargs:
return conn.getCategories(id=50)
ret = {}
for category in conn.getCategories(id=50):
if category['categoryCode'] != kwargs['code']:
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
|
Return a dict of all prices on the cloud provider.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L619-L643
|
[
"def get_conn(service='SoftLayer_Hardware'):\n '''\n Return a conn object for the passed VM data\n '''\n client = SoftLayer.Client(\n username=config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n ),\n api_key=config.get_cloud_config_value(\n 'apikey', get_configured_provider(), __opts__, search_global=False\n ),\n )\n return client[service]\n"
] |
# -*- coding: utf-8 -*-
'''
SoftLayer HW Cloud Module
=========================
The SoftLayer HW cloud module is used to control access to the SoftLayer
hardware cloud system
Use of this module only requires the ``apikey`` parameter. Set up the cloud
configuration at:
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/softlayer.conf``:
.. code-block:: yaml
my-softlayer-config:
# SoftLayer account api key
user: MYLOGIN
apikey: JVkbSJDGHSDKUKSDJfhsdklfjgsjdkflhjlsdfffhgdgjkenrtuinv
driver: softlayer_hw
The SoftLayer Python Library needs to be installed in order to use the
SoftLayer salt.cloud modules. See: https://pypi.python.org/pypi/SoftLayer
:depends: softlayer
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
import decimal
# Import salt cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
# Attempt to import softlayer lib
try:
import SoftLayer
HAS_SLLIBS = True
except ImportError:
HAS_SLLIBS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'softlayer_hw'
# Only load in this module if the SoftLayer configurations are in place
def __virtual__():
'''
Check for SoftLayer configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('apikey',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'softlayer': HAS_SLLIBS}
)
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def get_conn(service='SoftLayer_Hardware'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service]
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
locations = conn.getLocations(id=50)
for location in locations:
ret[location['id']] = {
'id': location['id'],
'name': location['name'],
'location': location['longName'],
}
available = conn.getAvailableLocations(id=50)
for location in available:
if location.get('isAvailable', 0) is 0:
continue
ret[location['locationId']]['available'] = True
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'server_core':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'os':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def get_location(vm_=None):
'''
Return the location to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
#default=DEFAULT_LOCATION,
search_global=False
)
)
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer_hw',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn(service='SoftLayer_Product_Order')
kwargs = {
'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
'quantity': 1,
'hardware': [{
'hostname': hostname,
'domain': domain,
}],
# Baremetal Package
'packageId': 50,
'prices': [
# Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
{'id': vm_['size']},
# HDD Ex: 19: 250GB SATA II
{'id': vm_['hdd']},
# Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
{'id': vm_['image']},
# The following items are currently required
# Reboot / Remote Console
{'id': '905'},
# 1 IP Address
{'id': '21'},
# Host Ping Monitoring
{'id': '55'},
# Email and Ticket Notifications
{'id': '57'},
# Automated Notification Response
{'id': '58'},
# Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': '420'},
# Nessus Vulnerability Assessment & Reporting
{'id': '418'},
],
}
optional_products = config.get_cloud_config_value(
'optional_products', vm_, __opts__, default=[]
)
for product in optional_products:
kwargs['prices'].append({'id': product})
# Default is 273 (100 Mbps Public & Private Networks)
port_speed = config.get_cloud_config_value(
'port_speed', vm_, __opts__, default=273
)
kwargs['prices'].append({'id': port_speed})
# Default is 1800 (0 GB Bandwidth)
bandwidth = config.get_cloud_config_value(
'bandwidth', vm_, __opts__, default=1800
)
kwargs['prices'].append({'id': bandwidth})
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['prices'].append({'id': post_uri})
vlan_id = config.get_cloud_config_value(
'vlan', vm_, __opts__, default=False
)
if vlan_id:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': vlan_id,
}
}
location = get_location(vm_)
if location:
kwargs['location'] = location
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.placeOrder(kwargs)
# Leaving the following line in, commented, for easy debugging
#response = conn.verifyOrder(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if 'primaryIpAddress' in nodes[hostname]:
return nodes[hostname]['primaryIpAddress']
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
ssh_connect_timeout = config.get_cloud_config_value(
# 15 minutes
'ssh_connect_timeout', vm_, __opts__, 900
)
if not salt.utils.cloud.wait_for_port(ip_address,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_passwd():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] \
and 'passwords' in node['operatingSystem'] \
and node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
passwd = salt.utils.cloud.wait_for_fun(
get_passwd,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default='root'
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getHardware(mask=mask)
for node in response:
ret[node['hostname']] = node
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['memoryCount'],
'cpus': nodes[node]['processorPhysicalCoreAmount'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from SoftLayer concerning a guest
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn(service='SoftLayer_Ticket')
response = conn.createCancelServerTicket(
{
'id': node['id'],
'reason': 'Salt Cloud Hardware Server Cancellation',
'content': 'Please cancel this server',
'cancelAssociatedItems': True,
'attachmentType': 'HARDWARE',
}
)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response
def list_vlans(call=None):
'''
List all VLANs associated with the account
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Account')
return conn.getNetworkVlans()
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Softlayer HW
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'softlayer_hw':
return {'Error': 'The requested profile does not belong to Softlayer HW'}
raw = {}
ret = {}
ret['per_hour'] = 0
conn = get_conn(service='SoftLayer_Product_Item_Price')
for item in profile:
if item in ('profile', 'provider', 'location'):
continue
price = conn.getObject(id=profile[item])
raw[item] = price
ret['per_hour'] += decimal.Decimal(price.get('hourlyRecurringFee', 0))
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def show_all_categories(call=None):
'''
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_categories function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Product_Package')
categories = []
for category in conn.getCategories(id=50):
categories.append(category['categoryCode'])
return {'category_codes': categories}
|
saltstack/salt
|
salt/cloud/clouds/softlayer_hw.py
|
show_all_categories
|
python
|
def show_all_categories(call=None):
'''
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_categories function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Product_Package')
categories = []
for category in conn.getCategories(id=50):
categories.append(category['categoryCode'])
return {'category_codes': categories}
|
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/softlayer_hw.py#L646-L663
|
[
"def get_conn(service='SoftLayer_Hardware'):\n '''\n Return a conn object for the passed VM data\n '''\n client = SoftLayer.Client(\n username=config.get_cloud_config_value(\n 'user', get_configured_provider(), __opts__, search_global=False\n ),\n api_key=config.get_cloud_config_value(\n 'apikey', get_configured_provider(), __opts__, search_global=False\n ),\n )\n return client[service]\n"
] |
# -*- coding: utf-8 -*-
'''
SoftLayer HW Cloud Module
=========================
The SoftLayer HW cloud module is used to control access to the SoftLayer
hardware cloud system
Use of this module only requires the ``apikey`` parameter. Set up the cloud
configuration at:
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/softlayer.conf``:
.. code-block:: yaml
my-softlayer-config:
# SoftLayer account api key
user: MYLOGIN
apikey: JVkbSJDGHSDKUKSDJfhsdklfjgsjdkflhjlsdfffhgdgjkenrtuinv
driver: softlayer_hw
The SoftLayer Python Library needs to be installed in order to use the
SoftLayer salt.cloud modules. See: https://pypi.python.org/pypi/SoftLayer
:depends: softlayer
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import time
import decimal
# Import salt cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
# Attempt to import softlayer lib
try:
import SoftLayer
HAS_SLLIBS = True
except ImportError:
HAS_SLLIBS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'softlayer_hw'
# Only load in this module if the SoftLayer configurations are in place
def __virtual__():
'''
Check for SoftLayer configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('apikey',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'softlayer': HAS_SLLIBS}
)
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def get_conn(service='SoftLayer_Hardware'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service]
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
locations = conn.getLocations(id=50)
for location in locations:
ret[location['id']] = {
'id': location['id'],
'name': location['name'],
'location': location['longName'],
}
available = conn.getAvailableLocations(id=50)
for location in available:
if location.get('isAvailable', 0) is 0:
continue
ret[location['locationId']]['available'] = True
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'server_core':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'os':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
def get_location(vm_=None):
'''
Return the location to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
#default=DEFAULT_LOCATION,
search_global=False
)
)
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'softlayer_hw',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
name = vm_['name']
hostname = name
domain = config.get_cloud_config_value(
'domain', vm_, __opts__, default=None
)
if domain is None:
SaltCloudSystemExit(
'A domain name is required for the SoftLayer driver.'
)
if vm_.get('use_fqdn'):
name = '.'.join([name, domain])
vm_['name'] = name
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(name),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', name)
conn = get_conn(service='SoftLayer_Product_Order')
kwargs = {
'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
'quantity': 1,
'hardware': [{
'hostname': hostname,
'domain': domain,
}],
# Baremetal Package
'packageId': 50,
'prices': [
# Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
{'id': vm_['size']},
# HDD Ex: 19: 250GB SATA II
{'id': vm_['hdd']},
# Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
{'id': vm_['image']},
# The following items are currently required
# Reboot / Remote Console
{'id': '905'},
# 1 IP Address
{'id': '21'},
# Host Ping Monitoring
{'id': '55'},
# Email and Ticket Notifications
{'id': '57'},
# Automated Notification Response
{'id': '58'},
# Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': '420'},
# Nessus Vulnerability Assessment & Reporting
{'id': '418'},
],
}
optional_products = config.get_cloud_config_value(
'optional_products', vm_, __opts__, default=[]
)
for product in optional_products:
kwargs['prices'].append({'id': product})
# Default is 273 (100 Mbps Public & Private Networks)
port_speed = config.get_cloud_config_value(
'port_speed', vm_, __opts__, default=273
)
kwargs['prices'].append({'id': port_speed})
# Default is 1800 (0 GB Bandwidth)
bandwidth = config.get_cloud_config_value(
'bandwidth', vm_, __opts__, default=1800
)
kwargs['prices'].append({'id': bandwidth})
post_uri = config.get_cloud_config_value(
'post_uri', vm_, __opts__, default=None
)
if post_uri:
kwargs['prices'].append({'id': post_uri})
vlan_id = config.get_cloud_config_value(
'vlan', vm_, __opts__, default=False
)
if vlan_id:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': vlan_id,
}
}
location = get_location(vm_)
if location:
kwargs['location'] = location
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(name),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
response = conn.placeOrder(kwargs)
# Leaving the following line in, commented, for easy debugging
#response = conn.verifyOrder(kwargs)
except Exception as exc:
log.error(
'Error creating %s on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s', name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if 'primaryIpAddress' in nodes[hostname]:
return nodes[hostname]['primaryIpAddress']
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
ssh_connect_timeout = config.get_cloud_config_value(
# 15 minutes
'ssh_connect_timeout', vm_, __opts__, 900
)
if not salt.utils.cloud.wait_for_port(ip_address,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_passwd():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id'] \
and 'passwords' in node['operatingSystem'] \
and node['operatingSystem']['passwords']:
return node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
passwd = salt.utils.cloud.wait_for_fun(
get_passwd,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default='root'
)
vm_['ssh_host'] = ip_address
vm_['password'] = passwd
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(response)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(name),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='SoftLayer_Account')
response = conn.getHardware(mask=mask)
for node in response:
ret[node['hostname']] = node
__utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['memoryCount'],
'cpus': nodes[node]['processorPhysicalCoreAmount'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from SoftLayer concerning a guest
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn(service='SoftLayer_Ticket')
response = conn.createCancelServerTicket(
{
'id': node['id'],
'reason': 'Salt Cloud Hardware Server Cancellation',
'content': 'Please cancel this server',
'cancelAssociatedItems': True,
'attachmentType': 'HARDWARE',
}
)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return response
def list_vlans(call=None):
'''
List all VLANs associated with the account
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
conn = get_conn(service='SoftLayer_Account')
return conn.getNetworkVlans()
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: 2015.8.0
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Softlayer HW
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'softlayer_hw':
return {'Error': 'The requested profile does not belong to Softlayer HW'}
raw = {}
ret = {}
ret['per_hour'] = 0
conn = get_conn(service='SoftLayer_Product_Item_Price')
for item in profile:
if item in ('profile', 'provider', 'location'):
continue
price = conn.getObject(id=profile[item])
raw[item] = price
ret['per_hour'] += decimal.Decimal(price.get('hourlyRecurringFee', 0))
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def show_all_prices(call=None, kwargs=None):
'''
Return a dict of all prices on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_prices function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn(service='SoftLayer_Product_Package')
if 'code' not in kwargs:
return conn.getCategories(id=50)
ret = {}
for category in conn.getCategories(id=50):
if category['categoryCode'] != kwargs['code']:
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
return ret
|
saltstack/salt
|
salt/modules/mysql.py
|
_connect
|
python
|
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
|
wrap authentication credentials here
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L329-L400
|
[
"def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
quote_identifier
|
python
|
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
|
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L562-L587
| null |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
_execute
|
python
|
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
|
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L590-L607
| null |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
query
|
python
|
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
|
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L610-L739
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
file_query
|
python
|
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
|
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L742-L813
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\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_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 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
status
|
python
|
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
|
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L816-L844
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
version
|
python
|
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
|
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L847-L874
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
slave_lag
|
python
|
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
|
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L877-L916
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
free_slave
|
python
|
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
|
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L919-L961
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_list
|
python
|
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
|
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L965-L995
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
alter_db
|
python
|
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
|
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L998-L1019
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def db_get(name, **connection_args):\n '''\n Return a list of databases of a MySQL server using the output\n from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM\n INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.db_get test\n '''\n dbc = _connect(**connection_args)\n if dbc is None:\n return []\n cur = dbc.cursor()\n qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '\n 'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')\n args = {\"dbname\": name}\n _execute(cur, qry, args)\n if cur.rowcount:\n rows = cur.fetchall()\n return {'character_set': rows[0][0],\n 'collate': rows[0][1]}\n return {}\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_get
|
python
|
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
|
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1022-L1046
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_tables
|
python
|
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
|
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1049-L1083
|
[
"def db_exists(name, **connection_args):\n '''\n Checks if a database exists on the MySQL server.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.db_exists 'dbname'\n '''\n dbc = _connect(**connection_args)\n if dbc is None:\n return False\n cur = dbc.cursor()\n # Warn: here db identifier is not backtyped but should be\n # escaped as a string value. Note also that LIKE special characters\n # '_' and '%' should also be escaped.\n args = {\"dbname\": name}\n qry = \"SHOW DATABASES LIKE %(dbname)s;\"\n try:\n _execute(cur, qry, args)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return False\n cur.fetchall()\n return cur.rowcount == 1\n",
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def quote_identifier(identifier, for_grants=False):\n r'''\n Return an identifier name (column, table, database, etc) escaped for MySQL\n\n This means surrounded by \"`\" character and escaping this character inside.\n It also means doubling the '%' character for MySQLdb internal usage.\n\n :param identifier: the table, column or database identifier\n\n :param for_grants: is False by default, when using database names on grant\n queries you should set it to True to also escape \"_\" and \"%\" characters as\n requested by MySQL. Note that theses characters should only be escaped when\n requesting grants on the database level (`my\\_\\%db`.*) but not for table\n level grants (`my_%db`.`foo`)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.quote_identifier 'foo`bar'\n '''\n if for_grants:\n return '`' + identifier.replace('`', '``').replace('_', r'\\_') \\\n .replace('%', r'%%') + '`'\n else:\n return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_exists
|
python
|
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
|
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1086-L1113
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_create
|
python
|
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
|
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1116-L1166
|
[
"def db_exists(name, **connection_args):\n '''\n Checks if a database exists on the MySQL server.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.db_exists 'dbname'\n '''\n dbc = _connect(**connection_args)\n if dbc is None:\n return False\n cur = dbc.cursor()\n # Warn: here db identifier is not backtyped but should be\n # escaped as a string value. Note also that LIKE special characters\n # '_' and '%' should also be escaped.\n args = {\"dbname\": name}\n qry = \"SHOW DATABASES LIKE %(dbname)s;\"\n try:\n _execute(cur, qry, args)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return False\n cur.fetchall()\n return cur.rowcount == 1\n",
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def quote_identifier(identifier, for_grants=False):\n r'''\n Return an identifier name (column, table, database, etc) escaped for MySQL\n\n This means surrounded by \"`\" character and escaping this character inside.\n It also means doubling the '%' character for MySQLdb internal usage.\n\n :param identifier: the table, column or database identifier\n\n :param for_grants: is False by default, when using database names on grant\n queries you should set it to True to also escape \"_\" and \"%\" characters as\n requested by MySQL. Note that theses characters should only be escaped when\n requesting grants on the database level (`my\\_\\%db`.*) but not for table\n level grants (`my_%db`.`foo`)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.quote_identifier 'foo`bar'\n '''\n if for_grants:\n return '`' + identifier.replace('`', '``').replace('_', r'\\_') \\\n .replace('%', r'%%') + '`'\n else:\n return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_remove
|
python
|
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
|
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1169-L1209
|
[
"def db_exists(name, **connection_args):\n '''\n Checks if a database exists on the MySQL server.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.db_exists 'dbname'\n '''\n dbc = _connect(**connection_args)\n if dbc is None:\n return False\n cur = dbc.cursor()\n # Warn: here db identifier is not backtyped but should be\n # escaped as a string value. Note also that LIKE special characters\n # '_' and '%' should also be escaped.\n args = {\"dbname\": name}\n qry = \"SHOW DATABASES LIKE %(dbname)s;\"\n try:\n _execute(cur, qry, args)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return False\n cur.fetchall()\n return cur.rowcount == 1\n",
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def quote_identifier(identifier, for_grants=False):\n r'''\n Return an identifier name (column, table, database, etc) escaped for MySQL\n\n This means surrounded by \"`\" character and escaping this character inside.\n It also means doubling the '%' character for MySQLdb internal usage.\n\n :param identifier: the table, column or database identifier\n\n :param for_grants: is False by default, when using database names on grant\n queries you should set it to True to also escape \"_\" and \"%\" characters as\n requested by MySQL. Note that theses characters should only be escaped when\n requesting grants on the database level (`my\\_\\%db`.*) but not for table\n level grants (`my_%db`.`foo`)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.quote_identifier 'foo`bar'\n '''\n if for_grants:\n return '`' + identifier.replace('`', '``').replace('_', r'\\_') \\\n .replace('%', r'%%') + '`'\n else:\n return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
user_list
|
python
|
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
|
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1213-L1237
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
user_exists
|
python
|
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
|
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1240-L1325
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def version(**connection_args):\n '''\n Return the version of a MySQL server using the output from the ``SELECT\n VERSION()`` query.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.version\n '''\n dbc = _connect(**connection_args)\n if dbc is None:\n return ''\n cur = dbc.cursor()\n qry = 'SELECT VERSION()'\n try:\n _execute(cur, qry)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return ''\n\n try:\n return salt.utils.data.decode(cur.fetchone()[0])\n except IndexError:\n return ''\n",
"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 _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def __password_column(**connection_args):\n dbc = _connect(**connection_args)\n if dbc is None:\n return 'Password'\n cur = dbc.cursor()\n qry = ('SELECT column_name from information_schema.COLUMNS '\n 'WHERE table_schema=%(schema)s and table_name=%(table)s '\n 'and column_name=%(column)s')\n args = {\n 'schema': 'mysql',\n 'table': 'user',\n 'column': 'Password'\n }\n _execute(cur, qry, args)\n if int(cur.rowcount) > 0:\n return 'Password'\n else:\n return 'authentication_string'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
user_info
|
python
|
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
|
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1328-L1358
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
user_create
|
python
|
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
|
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1361-L1471
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def version(**connection_args):\n '''\n Return the version of a MySQL server using the output from the ``SELECT\n VERSION()`` query.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.version\n '''\n dbc = _connect(**connection_args)\n if dbc is None:\n return ''\n cur = dbc.cursor()\n qry = 'SELECT VERSION()'\n try:\n _execute(cur, qry)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return ''\n\n try:\n return salt.utils.data.decode(cur.fetchone()[0])\n except IndexError:\n return ''\n",
"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 version_cmp(pkg1, pkg2, ignore_epoch=False):\n '''\n Compares two version strings using salt.utils.versions.LooseVersion. This\n is a fallback for providers which don't have a version comparison utility\n built into them. Return -1 if version1 < version2, 0 if version1 ==\n version2, and 1 if version1 > version2. Return None if there was a problem\n making the comparison.\n '''\n normalize = lambda x: six.text_type(x).split(':', 1)[-1] \\\n if ignore_epoch else six.text_type(x)\n pkg1 = normalize(pkg1)\n pkg2 = normalize(pkg2)\n\n try:\n # pylint: disable=no-member\n if LooseVersion(pkg1) < LooseVersion(pkg2):\n return -1\n elif LooseVersion(pkg1) == LooseVersion(pkg2):\n return 0\n elif LooseVersion(pkg1) > LooseVersion(pkg2):\n return 1\n except Exception as exc:\n log.exception(exc)\n return None\n",
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def user_exists(user,\n host='localhost',\n password=None,\n password_hash=None,\n passwordless=False,\n unix_socket=False,\n password_column=None,\n **connection_args):\n '''\n Checks if a user exists on the MySQL server. A login can be checked to see\n if passwordless login is permitted by omitting ``password`` and\n ``password_hash``, and using ``passwordless=True``.\n\n .. versionadded:: 0.16.2\n The ``passwordless`` option was added.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.user_exists 'username' 'hostname' 'password'\n salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'\n salt '*' mysql.user_exists 'username' passwordless=True\n salt '*' mysql.user_exists 'username' password_column='authentication_string'\n '''\n run_verify = False\n server_version = salt.utils.data.decode(version(**connection_args))\n if not server_version:\n last_err = __context__['mysql.error']\n err = 'MySQL Error: Unable to fetch current server version. Last error was: \"{}\"'.format(last_err)\n log.error(err)\n return False\n compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'\n dbc = _connect(**connection_args)\n # Did we fail to connect with the user we are checking\n # Its password might have previously change with the same command/state\n if dbc is None \\\n and __context__['mysql.error'] \\\n .startswith(\"MySQL Error 1045: Access denied for user '{0}'@\".format(user)) \\\n and password:\n # Clear the previous error\n __context__['mysql.error'] = None\n connection_args['connection_pass'] = password\n dbc = _connect(**connection_args)\n if dbc is None:\n return False\n\n if not password_column:\n password_column = __password_column(**connection_args)\n\n cur = dbc.cursor()\n qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '\n 'Host = %(host)s')\n args = {}\n args['user'] = user\n args['host'] = host\n\n if salt.utils.data.is_true(passwordless):\n if salt.utils.data.is_true(unix_socket):\n qry += ' AND plugin=%(unix_socket)s'\n args['unix_socket'] = 'unix_socket'\n else:\n qry += ' AND ' + password_column + ' = \\'\\''\n elif password:\n if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:\n run_verify = True\n else:\n _password = password\n qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'\n args['password'] = six.text_type(_password)\n elif password_hash:\n qry += ' AND ' + password_column + ' = %(password)s'\n args['password'] = password_hash\n\n if run_verify:\n if not verify_login(user, password, **connection_args):\n return False\n try:\n _execute(cur, qry, args)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return False\n\n return cur.rowcount == 1\n",
"def __password_column(**connection_args):\n dbc = _connect(**connection_args)\n if dbc is None:\n return 'Password'\n cur = dbc.cursor()\n qry = ('SELECT column_name from information_schema.COLUMNS '\n 'WHERE table_schema=%(schema)s and table_name=%(table)s '\n 'and column_name=%(column)s')\n args = {\n 'schema': 'mysql',\n 'table': 'user',\n 'column': 'Password'\n }\n _execute(cur, qry, args)\n if int(cur.rowcount) > 0:\n return 'Password'\n else:\n return 'authentication_string'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
user_chpass
|
python
|
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
|
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1474-L1602
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def version(**connection_args):\n '''\n Return the version of a MySQL server using the output from the ``SELECT\n VERSION()`` query.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.version\n '''\n dbc = _connect(**connection_args)\n if dbc is None:\n return ''\n cur = dbc.cursor()\n qry = 'SELECT VERSION()'\n try:\n _execute(cur, qry)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return ''\n\n try:\n return salt.utils.data.decode(cur.fetchone()[0])\n except IndexError:\n return ''\n",
"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 version_cmp(pkg1, pkg2, ignore_epoch=False):\n '''\n Compares two version strings using salt.utils.versions.LooseVersion. This\n is a fallback for providers which don't have a version comparison utility\n built into them. Return -1 if version1 < version2, 0 if version1 ==\n version2, and 1 if version1 > version2. Return None if there was a problem\n making the comparison.\n '''\n normalize = lambda x: six.text_type(x).split(':', 1)[-1] \\\n if ignore_epoch else six.text_type(x)\n pkg1 = normalize(pkg1)\n pkg2 = normalize(pkg2)\n\n try:\n # pylint: disable=no-member\n if LooseVersion(pkg1) < LooseVersion(pkg2):\n return -1\n elif LooseVersion(pkg1) == LooseVersion(pkg2):\n return 0\n elif LooseVersion(pkg1) > LooseVersion(pkg2):\n return 1\n except Exception as exc:\n log.exception(exc)\n return None\n",
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def __password_column(**connection_args):\n dbc = _connect(**connection_args)\n if dbc is None:\n return 'Password'\n cur = dbc.cursor()\n qry = ('SELECT column_name from information_schema.COLUMNS '\n 'WHERE table_schema=%(schema)s and table_name=%(table)s '\n 'and column_name=%(column)s')\n args = {\n 'schema': 'mysql',\n 'table': 'user',\n 'column': 'Password'\n }\n _execute(cur, qry, args)\n if int(cur.rowcount) > 0:\n return 'Password'\n else:\n return 'authentication_string'\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
user_remove
|
python
|
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
|
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1605-L1639
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def user_exists(user,\n host='localhost',\n password=None,\n password_hash=None,\n passwordless=False,\n unix_socket=False,\n password_column=None,\n **connection_args):\n '''\n Checks if a user exists on the MySQL server. A login can be checked to see\n if passwordless login is permitted by omitting ``password`` and\n ``password_hash``, and using ``passwordless=True``.\n\n .. versionadded:: 0.16.2\n The ``passwordless`` option was added.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.user_exists 'username' 'hostname' 'password'\n salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'\n salt '*' mysql.user_exists 'username' passwordless=True\n salt '*' mysql.user_exists 'username' password_column='authentication_string'\n '''\n run_verify = False\n server_version = salt.utils.data.decode(version(**connection_args))\n if not server_version:\n last_err = __context__['mysql.error']\n err = 'MySQL Error: Unable to fetch current server version. Last error was: \"{}\"'.format(last_err)\n log.error(err)\n return False\n compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'\n dbc = _connect(**connection_args)\n # Did we fail to connect with the user we are checking\n # Its password might have previously change with the same command/state\n if dbc is None \\\n and __context__['mysql.error'] \\\n .startswith(\"MySQL Error 1045: Access denied for user '{0}'@\".format(user)) \\\n and password:\n # Clear the previous error\n __context__['mysql.error'] = None\n connection_args['connection_pass'] = password\n dbc = _connect(**connection_args)\n if dbc is None:\n return False\n\n if not password_column:\n password_column = __password_column(**connection_args)\n\n cur = dbc.cursor()\n qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '\n 'Host = %(host)s')\n args = {}\n args['user'] = user\n args['host'] = host\n\n if salt.utils.data.is_true(passwordless):\n if salt.utils.data.is_true(unix_socket):\n qry += ' AND plugin=%(unix_socket)s'\n args['unix_socket'] = 'unix_socket'\n else:\n qry += ' AND ' + password_column + ' = \\'\\''\n elif password:\n if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:\n run_verify = True\n else:\n _password = password\n qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'\n args['password'] = six.text_type(_password)\n elif password_hash:\n qry += ' AND ' + password_column + ' = %(password)s'\n args['password'] = password_hash\n\n if run_verify:\n if not verify_login(user, password, **connection_args):\n return False\n try:\n _execute(cur, qry, args)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return False\n\n return cur.rowcount == 1\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_check
|
python
|
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
|
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1659-L1682
|
[
"def __check_table(name, table, **connection_args):\n dbc = _connect(**connection_args)\n if dbc is None:\n return {}\n cur = dbc.cursor(MySQLdb.cursors.DictCursor)\n s_name = quote_identifier(name)\n s_table = quote_identifier(table)\n # identifiers cannot be used as values\n qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)\n _execute(cur, qry)\n results = cur.fetchall()\n log.debug(results)\n return results\n",
"def db_tables(name, **connection_args):\n '''\n Shows the tables in the given MySQL database (if exists)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.db_tables 'database'\n '''\n if not db_exists(name, **connection_args):\n log.info('Database \\'%s\\' does not exist', name)\n return False\n\n dbc = _connect(**connection_args)\n if dbc is None:\n return []\n cur = dbc.cursor()\n s_name = quote_identifier(name)\n # identifiers cannot be used as values\n qry = 'SHOW TABLES IN {0}'.format(s_name)\n try:\n _execute(cur, qry)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return []\n\n ret = []\n results = cur.fetchall()\n for table in results:\n ret.append(table[0])\n log.debug(ret)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_repair
|
python
|
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
|
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1685-L1707
|
[
"def __repair_table(name, table, **connection_args):\n dbc = _connect(**connection_args)\n if dbc is None:\n return {}\n cur = dbc.cursor(MySQLdb.cursors.DictCursor)\n s_name = quote_identifier(name)\n s_table = quote_identifier(table)\n # identifiers cannot be used as values\n qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)\n _execute(cur, qry)\n results = cur.fetchall()\n log.debug(results)\n return results\n",
"def db_tables(name, **connection_args):\n '''\n Shows the tables in the given MySQL database (if exists)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.db_tables 'database'\n '''\n if not db_exists(name, **connection_args):\n log.info('Database \\'%s\\' does not exist', name)\n return False\n\n dbc = _connect(**connection_args)\n if dbc is None:\n return []\n cur = dbc.cursor()\n s_name = quote_identifier(name)\n # identifiers cannot be used as values\n qry = 'SHOW TABLES IN {0}'.format(s_name)\n try:\n _execute(cur, qry)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return []\n\n ret = []\n results = cur.fetchall()\n for table in results:\n ret.append(table[0])\n log.debug(ret)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
db_optimize
|
python
|
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
|
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1710-L1732
|
[
"def __optimize_table(name, table, **connection_args):\n dbc = _connect(**connection_args)\n if dbc is None:\n return {}\n cur = dbc.cursor(MySQLdb.cursors.DictCursor)\n s_name = quote_identifier(name)\n s_table = quote_identifier(table)\n # identifiers cannot be used as values\n qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)\n _execute(cur, qry)\n results = cur.fetchall()\n log.debug(results)\n return results\n",
"def db_tables(name, **connection_args):\n '''\n Shows the tables in the given MySQL database (if exists)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.db_tables 'database'\n '''\n if not db_exists(name, **connection_args):\n log.info('Database \\'%s\\' does not exist', name)\n return False\n\n dbc = _connect(**connection_args)\n if dbc is None:\n return []\n cur = dbc.cursor()\n s_name = quote_identifier(name)\n # identifiers cannot be used as values\n qry = 'SHOW TABLES IN {0}'.format(s_name)\n try:\n _execute(cur, qry)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return []\n\n ret = []\n results = cur.fetchall()\n for table in results:\n ret.append(table[0])\n log.debug(ret)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
__grant_generate
|
python
|
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
|
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1778-L1818
|
[
"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 quote_identifier(identifier, for_grants=False):\n r'''\n Return an identifier name (column, table, database, etc) escaped for MySQL\n\n This means surrounded by \"`\" character and escaping this character inside.\n It also means doubling the '%' character for MySQLdb internal usage.\n\n :param identifier: the table, column or database identifier\n\n :param for_grants: is False by default, when using database names on grant\n queries you should set it to True to also escape \"_\" and \"%\" characters as\n requested by MySQL. Note that theses characters should only be escaped when\n requesting grants on the database level (`my\\_\\%db`.*) but not for table\n level grants (`my_%db`.`foo`)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.quote_identifier 'foo`bar'\n '''\n if for_grants:\n return '`' + identifier.replace('`', '``').replace('_', r'\\_') \\\n .replace('%', r'%%') + '`'\n else:\n return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'\n",
"def __grant_normalize(grant):\n # MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that\n # grant_exists and grant_add ALL work correctly\n if grant == 'ALL':\n grant = 'ALL PRIVILEGES'\n\n # Grants are paste directly in SQL, must filter it\n exploded_grants = grant.split(\",\")\n for chkgrant in exploded_grants:\n if chkgrant.strip().upper() not in __grants__:\n raise Exception('Invalid grant : \\'{0}\\''.format(\n chkgrant\n ))\n\n return grant\n",
"def __ssl_option_sanitize(ssl_option):\n new_ssl_option = []\n\n # Like most other \"salt dsl\" YAML structures, ssl_option is a list of single-element dicts\n for opt in ssl_option:\n key = next(six.iterkeys(opt))\n\n normal_key = key.strip().upper()\n\n if normal_key not in __ssl_options__:\n raise Exception('Invalid SSL option : \\'{0}\\''.format(\n key\n ))\n\n if normal_key in __ssl_options_parameterized__:\n # SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so\n # we need to sanitize for single quotes...\n new_ssl_option.append(\"{0} '{1}'\".format(normal_key, opt[key].replace(\"'\", '')))\n # omit if falsey\n elif opt[key]:\n new_ssl_option.append(normal_key)\n\n return ' REQUIRE ' + ' AND '.join(new_ssl_option)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
user_grants
|
python
|
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
|
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1821-L1860
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def user_exists(user,\n host='localhost',\n password=None,\n password_hash=None,\n passwordless=False,\n unix_socket=False,\n password_column=None,\n **connection_args):\n '''\n Checks if a user exists on the MySQL server. A login can be checked to see\n if passwordless login is permitted by omitting ``password`` and\n ``password_hash``, and using ``passwordless=True``.\n\n .. versionadded:: 0.16.2\n The ``passwordless`` option was added.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.user_exists 'username' 'hostname' 'password'\n salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'\n salt '*' mysql.user_exists 'username' passwordless=True\n salt '*' mysql.user_exists 'username' password_column='authentication_string'\n '''\n run_verify = False\n server_version = salt.utils.data.decode(version(**connection_args))\n if not server_version:\n last_err = __context__['mysql.error']\n err = 'MySQL Error: Unable to fetch current server version. Last error was: \"{}\"'.format(last_err)\n log.error(err)\n return False\n compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'\n dbc = _connect(**connection_args)\n # Did we fail to connect with the user we are checking\n # Its password might have previously change with the same command/state\n if dbc is None \\\n and __context__['mysql.error'] \\\n .startswith(\"MySQL Error 1045: Access denied for user '{0}'@\".format(user)) \\\n and password:\n # Clear the previous error\n __context__['mysql.error'] = None\n connection_args['connection_pass'] = password\n dbc = _connect(**connection_args)\n if dbc is None:\n return False\n\n if not password_column:\n password_column = __password_column(**connection_args)\n\n cur = dbc.cursor()\n qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '\n 'Host = %(host)s')\n args = {}\n args['user'] = user\n args['host'] = host\n\n if salt.utils.data.is_true(passwordless):\n if salt.utils.data.is_true(unix_socket):\n qry += ' AND plugin=%(unix_socket)s'\n args['unix_socket'] = 'unix_socket'\n else:\n qry += ' AND ' + password_column + ' = \\'\\''\n elif password:\n if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:\n run_verify = True\n else:\n _password = password\n qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'\n args['password'] = six.text_type(_password)\n elif password_hash:\n qry += ' AND ' + password_column + ' = %(password)s'\n args['password'] = password_hash\n\n if run_verify:\n if not verify_login(user, password, **connection_args):\n return False\n try:\n _execute(cur, qry, args)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return False\n\n return cur.rowcount == 1\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
grant_exists
|
python
|
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
|
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1863-L1949
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def version(**connection_args):\n '''\n Return the version of a MySQL server using the output from the ``SELECT\n VERSION()`` query.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.version\n '''\n dbc = _connect(**connection_args)\n if dbc is None:\n return ''\n cur = dbc.cursor()\n qry = 'SELECT VERSION()'\n try:\n _execute(cur, qry)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return ''\n\n try:\n return salt.utils.data.decode(cur.fetchone()[0])\n except IndexError:\n return ''\n",
"def version_cmp(pkg1, pkg2, ignore_epoch=False):\n '''\n Compares two version strings using salt.utils.versions.LooseVersion. This\n is a fallback for providers which don't have a version comparison utility\n built into them. Return -1 if version1 < version2, 0 if version1 ==\n version2, and 1 if version1 > version2. Return None if there was a problem\n making the comparison.\n '''\n normalize = lambda x: six.text_type(x).split(':', 1)[-1] \\\n if ignore_epoch else six.text_type(x)\n pkg1 = normalize(pkg1)\n pkg2 = normalize(pkg2)\n\n try:\n # pylint: disable=no-member\n if LooseVersion(pkg1) < LooseVersion(pkg2):\n return -1\n elif LooseVersion(pkg1) == LooseVersion(pkg2):\n return 0\n elif LooseVersion(pkg1) > LooseVersion(pkg2):\n return 1\n except Exception as exc:\n log.exception(exc)\n return None\n",
"def _grant_to_tokens(grant):\n '''\n\n This should correspond fairly closely to the YAML rendering of a\n mysql_grants state which comes out as follows:\n\n OrderedDict([\n ('whatever_identifier',\n OrderedDict([\n ('mysql_grants.present',\n [\n OrderedDict([('database', 'testdb.*')]),\n OrderedDict([('user', 'testuser')]),\n OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),\n OrderedDict([('host', 'localhost')])\n ]\n )\n ])\n )\n ])\n\n :param grant: An un-parsed MySQL GRANT statement str, like\n \"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'\"\n or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.\n :return:\n A Python dict with the following keys/values:\n - user: MySQL User\n - host: MySQL host\n - grant: [grant1, grant2] (ala SELECT, USAGE, etc)\n - database: MySQL DB\n '''\n log.debug('_grant_to_tokens entry \\'%s\\'', grant)\n dict_mode = False\n if isinstance(grant, dict):\n dict_mode = True\n # Everything coming in dictionary form was made for a MySQLdb execute\n # call and contain a '%%' escaping of '%' characters for MySQLdb\n # that we should remove here.\n grant_sql = grant.get('qry', 'undefined').replace('%%', '%')\n sql_args = grant.get('args', {})\n host = sql_args.get('host', 'undefined')\n user = sql_args.get('user', 'undefined')\n else:\n grant_sql = grant\n user = ''\n # the replace part is for presence of ` character in the db name\n # the shell escape is \\` but mysql escape is ``. Spaces should not be\n # exploded as users or db names could contain spaces.\n # Examples of splitting:\n # \"GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*\n # TO 'foo'@'localhost' WITH GRANT OPTION\"\n # ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',\n # 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', \"'foo'\", '@',\n # \"'localhost'\", 'WITH', 'GRANT', 'OPTION']\n #\n # 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\\'\"sa;ltdb`.`tbl ``\\'\"xx`\n # TO \\'foo \\' bar\\'@\\'localhost\\''\n # ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',\n # '`te s.t\\'\"sa;ltdb`', '.', '`tbl `', '`\\'\"xx`', 'TO', \"'foo '\", \"bar'\",\n # '@', \"'localhost'\"]\n #\n # \"GRANT USAGE ON *.* TO 'user \\\";--,?:&/\\\\'@'localhost'\"\n # ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\\'user \";--,?:&/\\\\\\'',\n # '@', \"'localhost'\"]\n lex = shlex.shlex(grant_sql)\n lex.quotes = '\\'`'\n lex.whitespace_split = False\n lex.commenters = ''\n lex.wordchars += '\\\"'\n exploded_grant = list(lex)\n grant_tokens = []\n multiword_statement = []\n position_tracker = 1 # Skip the initial 'GRANT' word token\n database = ''\n phrase = 'grants'\n\n for token in exploded_grant[position_tracker:]:\n\n if token == ',' and phrase == 'grants':\n position_tracker += 1\n continue\n\n if token == 'ON' and phrase == 'grants':\n phrase = 'db'\n position_tracker += 1\n continue\n\n elif token == 'TO' and phrase == 'tables':\n phrase = 'user'\n position_tracker += 1\n continue\n\n elif token == '@' and phrase == 'pre-host':\n phrase = 'host'\n position_tracker += 1\n continue\n\n if phrase == 'grants':\n # Read-ahead\n if exploded_grant[position_tracker + 1] == ',' \\\n or exploded_grant[position_tracker + 1] == 'ON':\n # End of token detected\n if multiword_statement:\n multiword_statement.append(token)\n grant_tokens.append(' '.join(multiword_statement))\n multiword_statement = []\n else:\n grant_tokens.append(token)\n else: # This is a multi-word, ala LOCK TABLES\n multiword_statement.append(token)\n\n elif phrase == 'db':\n # the shlex splitter may have split on special database characters `\n database += token\n # Read-ahead\n try:\n if exploded_grant[position_tracker + 1] == '.':\n phrase = 'tables'\n except IndexError:\n break\n\n elif phrase == 'tables':\n database += token\n\n elif phrase == 'user':\n if dict_mode:\n break\n else:\n user += token\n # Read-ahead\n if exploded_grant[position_tracker + 1] == '@':\n phrase = 'pre-host'\n\n elif phrase == 'host':\n host = token\n break\n\n position_tracker += 1\n\n try:\n if not dict_mode:\n user = user.strip(\"'\")\n host = host.strip(\"'\")\n log.debug(\n 'grant to token \\'%s\\'::\\'%s\\'::\\'%s\\'::\\'%s\\'',\n user,\n host,\n grant_tokens,\n database\n )\n except UnboundLocalError:\n host = ''\n\n return dict(user=user,\n host=host,\n grant=grant_tokens,\n database=database)\n",
"def __grant_generate(grant,\n database,\n user,\n host='localhost',\n grant_option=False,\n escape=True,\n ssl_option=False):\n '''\n Validate grants and build the query that could set the given grants\n\n Note that this query contains arguments for user and host but not for\n grants or database.\n '''\n # TODO: Re-order the grant so it is according to the\n # SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)\n grant = re.sub(r'\\s*,\\s*', ', ', grant).upper()\n\n grant = __grant_normalize(grant)\n\n db_part = database.rpartition('.')\n dbc = db_part[0]\n table = db_part[2]\n\n if escape:\n if dbc != '*':\n # _ and % are authorized on GRANT queries and should get escaped\n # on the db name, but only if not requesting a table level grant\n dbc = quote_identifier(dbc, for_grants=(table == '*'))\n if table != '*':\n table = quote_identifier(table)\n # identifiers cannot be used as values, and same thing for grants\n qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)\n args = {}\n args['user'] = user\n args['host'] = host\n if ssl_option and isinstance(ssl_option, list):\n qry += __ssl_option_sanitize(ssl_option)\n if salt.utils.data.is_true(grant_option):\n qry += ' WITH GRANT OPTION'\n log.debug('Grant Query generated: %s args %s', qry, repr(args))\n return {'qry': qry, 'args': args}\n",
"def user_grants(user,\n host='localhost', **connection_args):\n '''\n Shows the grants for the given MySQL user (if it exists)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.user_grants 'frank' 'localhost'\n '''\n if not user_exists(user, host, **connection_args):\n log.info('User \\'%s\\'@\\'%s\\' does not exist', user, host)\n return False\n\n dbc = _connect(**connection_args)\n if dbc is None:\n return False\n cur = dbc.cursor()\n qry = 'SHOW GRANTS FOR %(user)s@%(host)s'\n args = {}\n args['user'] = user\n args['host'] = host\n try:\n _execute(cur, qry, args)\n except MySQLdb.OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return False\n\n ret = []\n results = salt.utils.data.decode(cur.fetchall())\n for grant in results:\n tmp = grant[0].split(' IDENTIFIED BY')[0]\n if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:\n tmp = '{0} WITH GRANT OPTION'.format(tmp)\n ret.append(tmp)\n log.debug(ret)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
grant_add
|
python
|
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
|
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1952-L2004
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def __grant_generate(grant,\n database,\n user,\n host='localhost',\n grant_option=False,\n escape=True,\n ssl_option=False):\n '''\n Validate grants and build the query that could set the given grants\n\n Note that this query contains arguments for user and host but not for\n grants or database.\n '''\n # TODO: Re-order the grant so it is according to the\n # SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)\n grant = re.sub(r'\\s*,\\s*', ', ', grant).upper()\n\n grant = __grant_normalize(grant)\n\n db_part = database.rpartition('.')\n dbc = db_part[0]\n table = db_part[2]\n\n if escape:\n if dbc != '*':\n # _ and % are authorized on GRANT queries and should get escaped\n # on the db name, but only if not requesting a table level grant\n dbc = quote_identifier(dbc, for_grants=(table == '*'))\n if table != '*':\n table = quote_identifier(table)\n # identifiers cannot be used as values, and same thing for grants\n qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)\n args = {}\n args['user'] = user\n args['host'] = host\n if ssl_option and isinstance(ssl_option, list):\n qry += __ssl_option_sanitize(ssl_option)\n if salt.utils.data.is_true(grant_option):\n qry += ' WITH GRANT OPTION'\n log.debug('Grant Query generated: %s args %s', qry, repr(args))\n return {'qry': qry, 'args': args}\n",
"def grant_exists(grant,\n database,\n user,\n host='localhost',\n grant_option=False,\n escape=True,\n **connection_args):\n '''\n Checks to see if a grant exists in the database\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.grant_exists \\\n 'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'\n '''\n\n server_version = salt.utils.data.decode(version(**connection_args))\n if not server_version:\n last_err = __context__['mysql.error']\n err = 'MySQL Error: Unable to fetch current server version. Last error was: \"{}\"'.format(last_err)\n log.error(err)\n return False\n if 'ALL' in grant:\n if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \\\n 'MariaDB' not in server_version:\n grant = ','.join([i for i in __all_privileges__])\n else:\n grant = 'ALL PRIVILEGES'\n\n try:\n target = __grant_generate(\n grant, database, user, host, grant_option, escape\n )\n except Exception:\n log.error('Error during grant generation.')\n return False\n\n grants = user_grants(user, host, **connection_args)\n\n if grants is False:\n log.error('Grant does not exist or may not be ordered properly. In some cases, '\n 'this could also indicate a connection error. Check your configuration.')\n return False\n\n # Combine grants that match the same database\n _grants = {}\n for grant in grants:\n grant_token = _grant_to_tokens(grant)\n if grant_token['database'] not in _grants:\n _grants[grant_token['database']] = {'user': grant_token['user'],\n 'database': grant_token['database'],\n 'host': grant_token['host'],\n 'grant': grant_token['grant']}\n else:\n _grants[grant_token['database']]['grant'].extend(grant_token['grant'])\n\n target_tokens = _grant_to_tokens(target)\n for database, grant_tokens in _grants.items():\n try:\n _grant_tokens = {}\n _target_tokens = {}\n\n _grant_matches = [True if i in grant_tokens['grant']\n else False for i in target_tokens['grant']]\n\n for item in ['user', 'database', 'host']:\n _grant_tokens[item] = grant_tokens[item].replace('\"', '').replace('\\\\', '').replace('`', '')\n _target_tokens[item] = target_tokens[item].replace('\"', '').replace('\\\\', '').replace('`', '')\n\n if _grant_tokens['user'] == _target_tokens['user'] and \\\n _grant_tokens['database'] == _target_tokens['database'] and \\\n _grant_tokens['host'] == _target_tokens['host'] and \\\n all(_grant_matches):\n return True\n else:\n log.debug('grants mismatch \\'%s\\'<>\\'%s\\'', grant_tokens, target_tokens)\n\n except Exception as exc: # Fallback to strict parsing\n log.exception(exc)\n if grants is not False and target in grants:\n log.debug('Grant exists.')\n return True\n\n log.debug('Grant does not exist, or is perhaps not ordered properly?')\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
grant_revoke
|
python
|
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
|
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L2007-L2081
|
[
"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 _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n",
"def quote_identifier(identifier, for_grants=False):\n r'''\n Return an identifier name (column, table, database, etc) escaped for MySQL\n\n This means surrounded by \"`\" character and escaping this character inside.\n It also means doubling the '%' character for MySQLdb internal usage.\n\n :param identifier: the table, column or database identifier\n\n :param for_grants: is False by default, when using database names on grant\n queries you should set it to True to also escape \"_\" and \"%\" characters as\n requested by MySQL. Note that theses characters should only be escaped when\n requesting grants on the database level (`my\\_\\%db`.*) but not for table\n level grants (`my_%db`.`foo`)\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.quote_identifier 'foo`bar'\n '''\n if for_grants:\n return '`' + identifier.replace('`', '``').replace('_', r'\\_') \\\n .replace('%', r'%%') + '`'\n else:\n return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'\n",
"def __grant_normalize(grant):\n # MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that\n # grant_exists and grant_add ALL work correctly\n if grant == 'ALL':\n grant = 'ALL PRIVILEGES'\n\n # Grants are paste directly in SQL, must filter it\n exploded_grants = grant.split(\",\")\n for chkgrant in exploded_grants:\n if chkgrant.strip().upper() not in __grants__:\n raise Exception('Invalid grant : \\'{0}\\''.format(\n chkgrant\n ))\n\n return grant\n",
"def grant_exists(grant,\n database,\n user,\n host='localhost',\n grant_option=False,\n escape=True,\n **connection_args):\n '''\n Checks to see if a grant exists in the database\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mysql.grant_exists \\\n 'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'\n '''\n\n server_version = salt.utils.data.decode(version(**connection_args))\n if not server_version:\n last_err = __context__['mysql.error']\n err = 'MySQL Error: Unable to fetch current server version. Last error was: \"{}\"'.format(last_err)\n log.error(err)\n return False\n if 'ALL' in grant:\n if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \\\n 'MariaDB' not in server_version:\n grant = ','.join([i for i in __all_privileges__])\n else:\n grant = 'ALL PRIVILEGES'\n\n try:\n target = __grant_generate(\n grant, database, user, host, grant_option, escape\n )\n except Exception:\n log.error('Error during grant generation.')\n return False\n\n grants = user_grants(user, host, **connection_args)\n\n if grants is False:\n log.error('Grant does not exist or may not be ordered properly. In some cases, '\n 'this could also indicate a connection error. Check your configuration.')\n return False\n\n # Combine grants that match the same database\n _grants = {}\n for grant in grants:\n grant_token = _grant_to_tokens(grant)\n if grant_token['database'] not in _grants:\n _grants[grant_token['database']] = {'user': grant_token['user'],\n 'database': grant_token['database'],\n 'host': grant_token['host'],\n 'grant': grant_token['grant']}\n else:\n _grants[grant_token['database']]['grant'].extend(grant_token['grant'])\n\n target_tokens = _grant_to_tokens(target)\n for database, grant_tokens in _grants.items():\n try:\n _grant_tokens = {}\n _target_tokens = {}\n\n _grant_matches = [True if i in grant_tokens['grant']\n else False for i in target_tokens['grant']]\n\n for item in ['user', 'database', 'host']:\n _grant_tokens[item] = grant_tokens[item].replace('\"', '').replace('\\\\', '').replace('`', '')\n _target_tokens[item] = target_tokens[item].replace('\"', '').replace('\\\\', '').replace('`', '')\n\n if _grant_tokens['user'] == _target_tokens['user'] and \\\n _grant_tokens['database'] == _target_tokens['database'] and \\\n _grant_tokens['host'] == _target_tokens['host'] and \\\n all(_grant_matches):\n return True\n else:\n log.debug('grants mismatch \\'%s\\'<>\\'%s\\'', grant_tokens, target_tokens)\n\n except Exception as exc: # Fallback to strict parsing\n log.exception(exc)\n if grants is not False and target in grants:\n log.debug('Grant exists.')\n return True\n\n log.debug('Grant does not exist, or is perhaps not ordered properly?')\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
processlist
|
python
|
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
|
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L2084-L2127
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
__do_query_into_hash
|
python
|
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
|
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L2130-L2173
|
[
"def _execute(cur, qry, args=None):\n '''\n Internal wrapper around MySQLdb cursor.execute() function\n\n MySQLDb does not apply the same filters when arguments are used with the\n query. For example '%' characters on the query must be encoded as '%%' and\n will be restored as '%' when arguments are applied. But when there're no\n arguments the '%%' is not managed. We cannot apply Identifier quoting in a\n predictable way if the query are not always applying the same filters. So\n this wrapper ensure this escape is not made if no arguments are used.\n '''\n if args is None or args == {}:\n qry = qry.replace('%%', '%')\n log.debug('Doing query: %s', qry)\n return cur.execute(qry)\n else:\n log.debug('Doing query: %s args: %s ', qry, repr(args))\n return cur.execute(qry, args)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
get_master_status
|
python
|
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
|
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L2176-L2207
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n",
"def __do_query_into_hash(conn, sql_str):\n '''\n Perform the query that is passed to it (sql_str).\n\n Returns:\n results in a dict.\n\n '''\n mod = sys._getframe().f_code.co_name\n log.debug('%s<--(%s)', mod, sql_str)\n\n rtn_results = []\n\n try:\n cursor = conn.cursor()\n except MySQLdb.MySQLError:\n log.error('%s: Can\\'t get cursor for SQL->%s', mod, sql_str)\n cursor.close()\n log.debug('%s-->', mod)\n return rtn_results\n\n try:\n _execute(cursor, sql_str)\n except MySQLdb.MySQLError:\n log.error('%s: try to execute : SQL->%s', mod, sql_str)\n cursor.close()\n log.debug('%s-->', mod)\n return rtn_results\n\n qrs = cursor.fetchall()\n\n for row_data in qrs:\n col_cnt = 0\n row = {}\n for col_data in cursor.description:\n col_name = col_data[0]\n row[col_name] = row_data[col_cnt]\n col_cnt += 1\n\n rtn_results.append(row)\n\n cursor.close()\n log.debug('%s-->', mod)\n return rtn_results\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
saltstack/salt
|
salt/modules/mysql.py
|
verify_login
|
python
|
def verify_login(user, password=None, **connection_args):
'''
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
'''
# Override the connection args for username and password
connection_args['connection_user'] = user
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
# Clear the mysql.error if unable to connect
# if the connection fails, we simply return False
if 'mysql.error' in __context__:
del __context__['mysql.error']
return False
return True
|
Attempt to login using the provided credentials.
If successful, return true. Otherwise, return False.
CLI Example:
.. code-block:: bash
salt '*' mysql.verify_login root password
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L2336-L2358
|
[
"def _connect(**kwargs):\n '''\n wrap authentication credentials here\n '''\n connargs = dict()\n\n def _connarg(name, key=None, get_opts=True):\n '''\n Add key to connargs, only if name exists in our kwargs or,\n if get_opts is true, as mysql.<name> in __opts__ or __pillar__\n\n If get_opts is true, evaluate in said order - kwargs, opts\n then pillar. To avoid collision with other functions,\n kwargs-based connection arguments are prefixed with 'connection_'\n (i.e. 'connection_host', 'connection_user', etc.).\n '''\n if key is None:\n key = name\n\n if name in kwargs:\n connargs[key] = kwargs[name]\n elif get_opts:\n prefix = 'connection_'\n if name.startswith(prefix):\n try:\n name = name[len(prefix):]\n except IndexError:\n return\n val = __salt__['config.option']('mysql.{0}'.format(name), None)\n if val is not None:\n connargs[key] = val\n\n # If a default file is explicitly passed to kwargs, don't grab the\n # opts/pillar settings, as it can override info in the defaults file\n if 'connection_default_file' in kwargs:\n get_opts = False\n else:\n get_opts = True\n\n _connarg('connection_host', 'host', get_opts)\n _connarg('connection_user', 'user', get_opts)\n _connarg('connection_pass', 'passwd', get_opts)\n _connarg('connection_port', 'port', get_opts)\n _connarg('connection_db', 'db', get_opts)\n _connarg('connection_conv', 'conv', get_opts)\n _connarg('connection_unix_socket', 'unix_socket', get_opts)\n _connarg('connection_default_file', 'read_default_file', get_opts)\n _connarg('connection_default_group', 'read_default_group', get_opts)\n # MySQLdb states that this is required for charset usage\n # but in fact it's more than it's internally activated\n # when charset is used, activating use_unicode here would\n # retrieve utf8 strings as unicode() objects in salt\n # and we do not want that.\n #_connarg('connection_use_unicode', 'use_unicode')\n connargs['use_unicode'] = False\n _connarg('connection_charset', 'charset')\n # Ensure MySQldb knows the format we use for queries with arguments\n MySQLdb.paramstyle = 'pyformat'\n\n if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)\n log.warning('MySQL password of None found. Attempting passwordless login.')\n connargs.pop('passwd')\n try:\n dbc = MySQLdb.connect(**connargs)\n except OperationalError as exc:\n err = 'MySQL Error {0}: {1}'.format(*exc.args)\n __context__['mysql.error'] = err\n log.error(err)\n return None\n\n dbc.autocommit(True)\n return dbc\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide MySQL compatibility to salt.
:depends: - MySQLdb Python module
.. note::
On CentOS 5 (and possibly RHEL 5) both MySQL-python and python26-mysqldb
need to be installed.
:configuration: In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs might look
like::
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
mysql.unix_socket: '/tmp/mysql.sock'
mysql.charset: 'utf8'
You can also use a defaults file::
mysql.default_file: '/etc/mysql/debian.cnf'
.. versionchanged:: 2014.1.0
\'charset\' connection argument added. This is a MySQL charset, not a python one.
.. versionchanged:: 0.16.2
Connection arguments from the minion config file can be overridden on the
CLI by using the arguments defined :mod:`here <salt.states.mysql_user>`.
Additionally, it is now possible to setup a user with no password.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import time
import logging
import re
import sys
import shlex
import os
# Import salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
# Import third party libs
from salt.ext import six
# pylint: disable=import-error
from salt.ext.six.moves import range, zip # pylint: disable=no-name-in-module,redefined-builtin
try:
# Trying to import MySQLdb
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
try:
# MySQLdb import failed, try to import PyMySQL
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb.constants import FIELD_TYPE, FLAG
from MySQLdb import OperationalError
except ImportError:
MySQLdb = None
log = logging.getLogger(__name__)
# TODO: this is not used anywhere in the code?
__opts__ = {}
__grants__ = [
'ALL PRIVILEGES',
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GRANT OPTION',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'USAGE',
'XA_RECOVER_ADMIN'
]
__ssl_options_parameterized__ = [
'CIPHER',
'ISSUER',
'SUBJECT'
]
__ssl_options__ = __ssl_options_parameterized__ + [
'SSL',
'X509'
]
__all_privileges__ = [
'ALTER',
'ALTER ROUTINE',
'BACKUP_ADMIN',
'BINLOG_ADMIN',
'CONNECTION_ADMIN',
'CREATE',
'CREATE ROLE',
'CREATE ROUTINE',
'CREATE TABLESPACE',
'CREATE TEMPORARY TABLES',
'CREATE USER',
'CREATE VIEW',
'DELETE',
'DROP',
'DROP ROLE',
'ENCRYPTION_KEY_ADMIN',
'EVENT',
'EXECUTE',
'FILE',
'GROUP_REPLICATION_ADMIN',
'INDEX',
'INSERT',
'LOCK TABLES',
'PERSIST_RO_VARIABLES_ADMIN',
'PROCESS',
'REFERENCES',
'RELOAD',
'REPLICATION CLIENT',
'REPLICATION SLAVE',
'REPLICATION_SLAVE_ADMIN',
'RESOURCE_GROUP_ADMIN',
'RESOURCE_GROUP_USER',
'ROLE_ADMIN',
'SELECT',
'SET_USER_ID',
'SHOW DATABASES',
'SHOW VIEW',
'SHUTDOWN',
'SUPER',
'SYSTEM_VARIABLES_ADMIN',
'TRIGGER',
'UPDATE',
'XA_RECOVER_ADMIN'
]
r'''
DEVELOPER NOTE: ABOUT arguments management, escapes, formats, arguments and
security of SQL.
A general rule of SQL security is to use queries with _execute call in this
code using args parameter to let MySQLdb manage the arguments proper escaping.
Another way of escaping values arguments could be '{0!r}'.format(), using
__repr__ to ensure things get properly used as strings. But this could lead
to three problems:
* In ANSI mode, which is available on MySQL, but not by default, double
quotes " should not be used as a string delimiters, in ANSI mode this is an
identifier delimiter (like `).
* Some rare exploits with bad multibytes management, either on python or
MySQL could defeat this barrier, bindings internal escape functions
should manage theses cases.
* Unicode strings in Python 2 will include the 'u' before the repr'ed string,
like so:
Python 2.7.10 (default, May 26 2015, 04:16:29)
[GCC 5.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'something something {0!r}'.format(u'foo')
u"something something u'foo'"
So query with arguments should use a paramstyle defined in PEP249:
http://www.python.org/dev/peps/pep-0249/#paramstyle
We use pyformat, which means 'SELECT * FROM foo WHERE bar=%(myval)s'
used with {'myval': 'some user input'}
So far so good. But this cannot be used for identifier escapes. Identifiers
are database names, table names and column names. Theses names are not values
and do not follow the same escape rules (see quote_identifier function for
details on `_ and % escape policies on identifiers). Using value escaping on
identifier could fool the SQL engine (badly escaping quotes and not doubling
` characters. So for identifiers a call to quote_identifier should be done and
theses identifiers should then be added in strings with format, but without
__repr__ filter.
Note also that when using query with arguments in _execute all '%' characters
used in the query should get escaped to '%%' fo MySQLdb, but should not be
escaped if the query runs without arguments. This is managed by _execute() and
quote_identifier. This is not the same as escaping '%' to '\%' or '_' to '\%'
when using a LIKE query (example in db_exists), as this escape is there to
avoid having _ or % characters interpreted in LIKE queries. The string parted
of the first query could become (still used with args dictionary for myval):
'SELECT * FROM {0} WHERE bar=%(myval)s'.format(quote_identifier('user input'))
Check integration tests if you find a hole in theses strings and escapes rules
Finally some examples to sum up.
Given a name f_o%o`b'a"r, in python that would be """f_o%o`b'a"r""". I'll
avoid python syntax for clarity:
The MySQL way of writing this name is:
value : 'f_o%o`b\'a"r' (managed by MySQLdb)
identifier : `f_o%o``b'a"r`
db identifier in general GRANT: `f\_o\%o``b'a"r`
db identifier in table GRANT : `f_o%o``b'a"r`
in mySQLdb, query with args : `f_o%%o``b'a"r` (as identifier)
in mySQLdb, query without args: `f_o%o``b'a"r` (as identifier)
value in a LIKE query : 'f\_o\%o`b\'a"r' (quotes managed by MySQLdb)
And theses could be mixed, in a like query value with args: 'f\_o\%%o`b\'a"r'
'''
def __virtual__():
'''
Confirm that a python mysql client is installed.
'''
return bool(MySQLdb), 'No python mysql client installed.' if MySQLdb is None else ''
def __check_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'CHECK TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __repair_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'REPAIR TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __optimize_table(name, table, **connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
s_name = quote_identifier(name)
s_table = quote_identifier(table)
# identifiers cannot be used as values
qry = 'OPTIMIZE TABLE {0}.{1}'.format(s_name, s_table)
_execute(cur, qry)
results = cur.fetchall()
log.debug(results)
return results
def __password_column(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return 'Password'
cur = dbc.cursor()
qry = ('SELECT column_name from information_schema.COLUMNS '
'WHERE table_schema=%(schema)s and table_name=%(table)s '
'and column_name=%(column)s')
args = {
'schema': 'mysql',
'table': 'user',
'column': 'Password'
}
_execute(cur, qry, args)
if int(cur.rowcount) > 0:
return 'Password'
else:
return 'authentication_string'
def _connect(**kwargs):
'''
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None, get_opts=True):
'''
Add key to connargs, only if name exists in our kwargs or,
if get_opts is true, as mysql.<name> in __opts__ or __pillar__
If get_opts is true, evaluate in said order - kwargs, opts
then pillar. To avoid collision with other functions,
kwargs-based connection arguments are prefixed with 'connection_'
(i.e. 'connection_host', 'connection_user', etc.).
'''
if key is None:
key = name
if name in kwargs:
connargs[key] = kwargs[name]
elif get_opts:
prefix = 'connection_'
if name.startswith(prefix):
try:
name = name[len(prefix):]
except IndexError:
return
val = __salt__['config.option']('mysql.{0}'.format(name), None)
if val is not None:
connargs[key] = val
# If a default file is explicitly passed to kwargs, don't grab the
# opts/pillar settings, as it can override info in the defaults file
if 'connection_default_file' in kwargs:
get_opts = False
else:
get_opts = True
_connarg('connection_host', 'host', get_opts)
_connarg('connection_user', 'user', get_opts)
_connarg('connection_pass', 'passwd', get_opts)
_connarg('connection_port', 'port', get_opts)
_connarg('connection_db', 'db', get_opts)
_connarg('connection_conv', 'conv', get_opts)
_connarg('connection_unix_socket', 'unix_socket', get_opts)
_connarg('connection_default_file', 'read_default_file', get_opts)
_connarg('connection_default_group', 'read_default_group', get_opts)
# MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
# Ensure MySQldb knows the format we use for queries with arguments
MySQLdb.paramstyle = 'pyformat'
if connargs.get('passwd', True) is None: # If present but set to None. (Extreme edge case.)
log.warning('MySQL password of None found. Attempting passwordless login.')
connargs.pop('passwd')
try:
dbc = MySQLdb.connect(**connargs)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return None
dbc.autocommit(True)
return dbc
def _grant_to_tokens(grant):
'''
This should correspond fairly closely to the YAML rendering of a
mysql_grants state which comes out as follows:
OrderedDict([
('whatever_identifier',
OrderedDict([
('mysql_grants.present',
[
OrderedDict([('database', 'testdb.*')]),
OrderedDict([('user', 'testuser')]),
OrderedDict([('grant', 'ALTER, SELECT, LOCK TABLES')]),
OrderedDict([('host', 'localhost')])
]
)
])
)
])
:param grant: An un-parsed MySQL GRANT statement str, like
"GRANT SELECT, ALTER, LOCK TABLES ON `mydb`.* TO 'testuser'@'localhost'"
or a dictionary with 'qry' and 'args' keys for 'user' and 'host'.
:return:
A Python dict with the following keys/values:
- user: MySQL User
- host: MySQL host
- grant: [grant1, grant2] (ala SELECT, USAGE, etc)
- database: MySQL DB
'''
log.debug('_grant_to_tokens entry \'%s\'', grant)
dict_mode = False
if isinstance(grant, dict):
dict_mode = True
# Everything coming in dictionary form was made for a MySQLdb execute
# call and contain a '%%' escaping of '%' characters for MySQLdb
# that we should remove here.
grant_sql = grant.get('qry', 'undefined').replace('%%', '%')
sql_args = grant.get('args', {})
host = sql_args.get('host', 'undefined')
user = sql_args.get('user', 'undefined')
else:
grant_sql = grant
user = ''
# the replace part is for presence of ` character in the db name
# the shell escape is \` but mysql escape is ``. Spaces should not be
# exploded as users or db names could contain spaces.
# Examples of splitting:
# "GRANT SELECT, LOCK TABLES, UPDATE, CREATE ON `test ``(:=saltdb)`.*
# TO 'foo'@'localhost' WITH GRANT OPTION"
# ['GRANT', 'SELECT', ',', 'LOCK', 'TABLES', ',', 'UPDATE', ',', 'CREATE',
# 'ON', '`test `', '`(:=saltdb)`', '.', '*', 'TO', "'foo'", '@',
# "'localhost'", 'WITH', 'GRANT', 'OPTION']
#
# 'GRANT SELECT, INSERT, UPDATE, CREATE ON `te s.t\'"sa;ltdb`.`tbl ``\'"xx`
# TO \'foo \' bar\'@\'localhost\''
# ['GRANT', 'SELECT', ',', 'INSERT', ',', 'UPDATE', ',', 'CREATE', 'ON',
# '`te s.t\'"sa;ltdb`', '.', '`tbl `', '`\'"xx`', 'TO', "'foo '", "bar'",
# '@', "'localhost'"]
#
# "GRANT USAGE ON *.* TO 'user \";--,?:&/\\'@'localhost'"
# ['GRANT', 'USAGE', 'ON', '*', '.', '*', 'TO', '\'user ";--,?:&/\\\'',
# '@', "'localhost'"]
lex = shlex.shlex(grant_sql)
lex.quotes = '\'`'
lex.whitespace_split = False
lex.commenters = ''
lex.wordchars += '\"'
exploded_grant = list(lex)
grant_tokens = []
multiword_statement = []
position_tracker = 1 # Skip the initial 'GRANT' word token
database = ''
phrase = 'grants'
for token in exploded_grant[position_tracker:]:
if token == ',' and phrase == 'grants':
position_tracker += 1
continue
if token == 'ON' and phrase == 'grants':
phrase = 'db'
position_tracker += 1
continue
elif token == 'TO' and phrase == 'tables':
phrase = 'user'
position_tracker += 1
continue
elif token == '@' and phrase == 'pre-host':
phrase = 'host'
position_tracker += 1
continue
if phrase == 'grants':
# Read-ahead
if exploded_grant[position_tracker + 1] == ',' \
or exploded_grant[position_tracker + 1] == 'ON':
# End of token detected
if multiword_statement:
multiword_statement.append(token)
grant_tokens.append(' '.join(multiword_statement))
multiword_statement = []
else:
grant_tokens.append(token)
else: # This is a multi-word, ala LOCK TABLES
multiword_statement.append(token)
elif phrase == 'db':
# the shlex splitter may have split on special database characters `
database += token
# Read-ahead
try:
if exploded_grant[position_tracker + 1] == '.':
phrase = 'tables'
except IndexError:
break
elif phrase == 'tables':
database += token
elif phrase == 'user':
if dict_mode:
break
else:
user += token
# Read-ahead
if exploded_grant[position_tracker + 1] == '@':
phrase = 'pre-host'
elif phrase == 'host':
host = token
break
position_tracker += 1
try:
if not dict_mode:
user = user.strip("'")
host = host.strip("'")
log.debug(
'grant to token \'%s\'::\'%s\'::\'%s\'::\'%s\'',
user,
host,
grant_tokens,
database
)
except UnboundLocalError:
host = ''
return dict(user=user,
host=host,
grant=grant_tokens,
database=database)
def quote_identifier(identifier, for_grants=False):
r'''
Return an identifier name (column, table, database, etc) escaped for MySQL
This means surrounded by "`" character and escaping this character inside.
It also means doubling the '%' character for MySQLdb internal usage.
:param identifier: the table, column or database identifier
:param for_grants: is False by default, when using database names on grant
queries you should set it to True to also escape "_" and "%" characters as
requested by MySQL. Note that theses characters should only be escaped when
requesting grants on the database level (`my\_\%db`.*) but not for table
level grants (`my_%db`.`foo`)
CLI Example:
.. code-block:: bash
salt '*' mysql.quote_identifier 'foo`bar'
'''
if for_grants:
return '`' + identifier.replace('`', '``').replace('_', r'\_') \
.replace('%', r'%%') + '`'
else:
return '`' + identifier.replace('`', '``').replace('%', '%%') + '`'
def _execute(cur, qry, args=None):
'''
Internal wrapper around MySQLdb cursor.execute() function
MySQLDb does not apply the same filters when arguments are used with the
query. For example '%' characters on the query must be encoded as '%%' and
will be restored as '%' when arguments are applied. But when there're no
arguments the '%%' is not managed. We cannot apply Identifier quoting in a
predictable way if the query are not always applying the same filters. So
this wrapper ensure this escape is not made if no arguments are used.
'''
if args is None or args == {}:
qry = qry.replace('%%', '%')
log.debug('Doing query: %s', qry)
return cur.execute(qry)
else:
log.debug('Doing query: %s args: %s ', qry, repr(args))
return cur.execute(qry, args)
def query(database, query, **connection_args):
'''
Run an arbitrary SQL query and return the results or
the number of affected rows.
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "UPDATE mytable set myfield=1 limit 1"
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb "SELECT id,name,cash from users limit 3"
Return data:
.. code-block:: python
{'columns': ('id', 'name', 'cash'),
'query time': {'human': '1.0ms', 'raw': '0.001'},
'results': ((1L, 'User 1', Decimal('110.000000')),
(2L, 'User 2', Decimal('215.636756')),
(3L, 'User 3', Decimal('0.040000'))),
'rows returned': 3L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'INSERT into users values (null,"user 4", 5)'
Return data:
.. code-block:: python
{'query time': {'human': '25.6ms', 'raw': '0.02563'}, 'rows affected': 1L}
CLI Example:
.. code-block:: bash
salt '*' mysql.query mydb 'DELETE from users where id = 4 limit 1'
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
Jinja Example: Run a query on ``mydb`` and use row 0, column 0's data.
.. code-block:: jinja
{{ salt['mysql.query']('mydb', 'SELECT info from mytable limit 1')['results'][0][0] }}
'''
# Doesn't do anything about sql warnings, e.g. empty values on an insert.
# I don't think it handles multiple queries at once, so adding "commit"
# might not work.
# The following 3 lines stops MySQLdb from converting the MySQL results
# into Python objects. It leaves them as strings.
orig_conv = MySQLdb.converters.conversions
conv_iter = iter(orig_conv)
conv = dict(zip(conv_iter, [str] * len(orig_conv)))
# some converters are lists, do not break theses
conv_mysqldb = {'MYSQLDB': True}
if conv_mysqldb.get(MySQLdb.__package__.upper()):
conv[FIELD_TYPE.BLOB] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VAR_STRING] = [
(FLAG.BINARY, str),
]
conv[FIELD_TYPE.VARCHAR] = [
(FLAG.BINARY, str),
]
connection_args.update({'connection_db': database, 'connection_conv': conv})
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
start = time.time()
log.debug('Using db: %s to run query %s', database, query)
try:
affected = _execute(cur, query)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
results = cur.fetchall()
elapsed = (time.time() - start)
if elapsed < 0.200:
elapsed_h = str(round(elapsed * 1000, 1)) + 'ms'
else:
elapsed_h = str(round(elapsed, 2)) + 's'
ret = {}
ret['query time'] = {'human': elapsed_h, 'raw': str(round(elapsed, 5))}
select_keywords = ["SELECT", "SHOW", "DESC"]
select_query = False
for keyword in select_keywords:
if query.upper().strip().startswith(keyword):
select_query = True
break
if select_query:
ret['rows returned'] = affected
columns = ()
for column in cur.description:
columns += (column[0],)
ret['columns'] = columns
ret['results'] = results
return ret
else:
ret['rows affected'] = affected
return ret
def file_query(database, file_name, **connection_args):
'''
Run an arbitrary SQL query from the specified file and return the
the number of affected rows.
.. versionadded:: 2017.7.0
database
database to run script inside
file_name
File name of the script. This can be on the minion, or a file that is reachable by the fileserver
CLI Example:
.. code-block:: bash
salt '*' mysql.file_query mydb file_name=/tmp/sqlfile.sql
salt '*' mysql.file_query mydb file_name=salt://sqlfile.sql
Return data:
.. code-block:: python
{'query time': {'human': '39.0ms', 'raw': '0.03899'}, 'rows affected': 1L}
'''
if any(file_name.startswith(proto) for proto in ('salt://', 'http://', 'https://', 'swift://', 's3://')):
file_name = __salt__['cp.cache_file'](file_name)
if os.path.exists(file_name):
with salt.utils.files.fopen(file_name, 'r') as ifile:
contents = salt.utils.stringutils.to_unicode(ifile.read())
else:
log.error('File "%s" does not exist', file_name)
return False
query_string = ""
ret = {'rows returned': 0, 'columns': [], 'results': [], 'rows affected': 0, 'query time': {'raw': 0}}
for line in contents.splitlines():
if re.match(r'--', line): # ignore sql comments
continue
if not re.search(r'[^-;]+;', line): # keep appending lines that don't end in ;
query_string = query_string + line
else:
query_string = query_string + line # append lines that end with ; and run query
query_result = query(database, query_string, **connection_args)
query_string = ""
if query_result is False:
# Fail out on error
return False
if 'query time' in query_result:
ret['query time']['raw'] += float(query_result['query time']['raw'])
if 'rows returned' in query_result:
ret['rows returned'] += query_result['rows returned']
if 'columns' in query_result:
ret['columns'].append(query_result['columns'])
if 'results' in query_result:
ret['results'].append(query_result['results'])
if 'rows affected' in query_result:
ret['rows affected'] += query_result['rows affected']
ret['query time']['human'] = six.text_type(round(float(ret['query time']['raw']), 2)) + 's'
ret['query time']['raw'] = round(float(ret['query time']['raw']), 5)
# Remove empty keys in ret
ret = {k: v for k, v in six.iteritems(ret) if v}
return ret
def status(**connection_args):
'''
Return the status of a MySQL server using the output from the ``SHOW
STATUS`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.status
'''
dbc = _connect(**connection_args)
if dbc is None:
return {}
cur = dbc.cursor()
qry = 'SHOW STATUS'
try:
_execute(cur, qry)
except OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return {}
ret = {}
for _ in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version(**connection_args):
'''
Return the version of a MySQL server using the output from the ``SELECT
VERSION()`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.version
'''
dbc = _connect(**connection_args)
if dbc is None:
return ''
cur = dbc.cursor()
qry = 'SELECT VERSION()'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return ''
try:
return salt.utils.data.decode(cur.fetchone()[0])
except IndexError:
return ''
def slave_lag(**connection_args):
'''
Return the number of seconds that a slave SQL server is lagging behind the
master, if the host is not a slave it will return -1. If the server is
configured to be a slave for replication but slave IO is not running then
-2 will be returned. If there was an error connecting to the database or
checking the slave status, -3 will be returned.
CLI Example:
.. code-block:: bash
salt '*' mysql.slave_lag
'''
dbc = _connect(**connection_args)
if dbc is None:
return -3
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return -3
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
# in this case. Could probably check to see if Slave_IO_Running and
# Slave_SQL_Running are both set to 'Yes' as well to be really really
# sure that it is a slave.
return -1
else:
if results['Slave_IO_Running'] == 'Yes':
return results['Seconds_Behind_Master']
else:
# Replication is broken if you get here.
return -2
def free_slave(**connection_args):
'''
Frees a slave from its master. This is a WIP, do not use.
CLI Example:
.. code-block:: bash
salt '*' mysql.free_slave
'''
slave_db = _connect(**connection_args)
if slave_db is None:
return ''
slave_cur = slave_db.cursor(MySQLdb.cursors.DictCursor)
slave_cur.execute('show slave status')
slave_status = slave_cur.fetchone()
master = {'host': slave_status['Master_Host']}
try:
# Try to connect to the master and flush logs before promoting to
# master. This may fail if the master is no longer available.
# I am also assuming that the admin password is the same on both
# servers here, and only overriding the host option in the connect
# function.
master_db = _connect(**master)
if master_db is None:
return ''
master_cur = master_db.cursor()
master_cur.execute('flush logs')
master_db.close()
except MySQLdb.OperationalError:
pass
slave_cur.execute('stop slave')
slave_cur.execute('reset master')
slave_cur.execute('change master to MASTER_HOST=''')
slave_cur.execute('show slave status')
results = slave_cur.fetchone()
if results is None:
return 'promoted'
else:
return 'failed'
# Database related actions
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = 'SHOW DATABASES'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for dbs in results:
ret.append(dbs[0])
log.debug(ret)
return ret
def alter_db(name, character_set=None, collate=None, **connection_args):
'''
Modify database using ``ALTER DATABASE %(dbname)s CHARACTER SET %(charset)s
COLLATE %(collation)s;`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.alter_db testdb charset='latin1'
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
existing = db_get(name, **connection_args)
qry = 'ALTER DATABASE `{0}` CHARACTER SET {1} COLLATE {2};'.format(
name.replace('%', r'\%').replace('_', r'\_'),
character_set or existing.get('character_set'),
collate or existing.get('collate'))
args = {}
_execute(cur, qry, args)
def db_get(name, **connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='dbname';`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_get test
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry = ('SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM '
'INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=%(dbname)s;')
args = {"dbname": name}
_execute(cur, qry, args)
if cur.rowcount:
rows = cur.fetchall()
return {'character_set': rows[0][0],
'collate': rows[0][1]}
return {}
def db_tables(name, **connection_args):
'''
Shows the tables in the given MySQL database (if exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.db_tables 'database'
'''
if not db_exists(name, **connection_args):
log.info('Database \'%s\' does not exist', name)
return False
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'SHOW TABLES IN {0}'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
ret = []
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug(ret)
return ret
def db_exists(name, **connection_args):
'''
Checks if a database exists on the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_exists 'dbname'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Warn: here db identifier is not backtyped but should be
# escaped as a string value. Note also that LIKE special characters
# '_' and '%' should also be escaped.
args = {"dbname": name}
qry = "SHOW DATABASES LIKE %(dbname)s;"
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
cur.fetchall()
return cur.rowcount == 1
def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
def db_remove(name, **connection_args):
'''
Removes a databases from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists(name, **connection_args):
log.info('DB \'%s\' does not exist', name)
return False
if name in ('mysql', 'information_scheme'):
log.info('DB \'%s\' may not be removed', name)
return False
# db does exists, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'DROP DATABASE {0};'.format(s_name)
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not db_exists(name, **connection_args):
log.info('Database \'%s\' has been removed', name)
return True
log.info('Database \'%s\' has not been removed', name)
return False
# User related actions
def user_list(**connection_args):
'''
Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return []
results = cur.fetchall()
log.debug(results)
return results
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
salt '*' mysql.user_exists 'username' 'hostname' 'password'
salt '*' mysql.user_exists 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_exists 'username' passwordless=True
salt '*' mysql.user_exists 'username' password_column='authentication_string'
'''
run_verify = False
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
dbc = _connect(**connection_args)
# Did we fail to connect with the user we are checking
# Its password might have previously change with the same command/state
if dbc is None \
and __context__['mysql.error'] \
.startswith("MySQL Error 1045: Access denied for user '{0}'@".format(user)) \
and password:
# Clear the previous error
__context__['mysql.error'] = None
connection_args['connection_pass'] = password
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = ('SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
if salt.utils.data.is_true(passwordless):
if salt.utils.data.is_true(unix_socket):
qry += ' AND plugin=%(unix_socket)s'
args['unix_socket'] = 'unix_socket'
else:
qry += ' AND ' + password_column + ' = \'\''
elif password:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
run_verify = True
else:
_password = password
qry += ' AND ' + password_column + ' = PASSWORD(%(password)s)'
args['password'] = six.text_type(_password)
elif password_hash:
qry += ' AND ' + password_column + ' = %(password)s'
args['password'] = password_hash
if run_verify:
if not verify_login(user, password, **connection_args):
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
return cur.rowcount == 1
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = ('SELECT * FROM mysql.user WHERE User = %(user)s AND '
'Host = %(host)s')
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
result = cur.fetchone()
log.debug(result)
return result
def user_create(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Creates a MySQL user
host
Host for which this user/password combo applies
password
The password to use for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
unix_socket
If ``True`` and allow_passwordless is ``True`` then will be used unix_socket auth plugin.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_create 'username' 'hostname' 'password'
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
salt '*' mysql.user_create 'username' 'hostname' allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
if user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' already exists', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
qry = 'CREATE USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
if password is not None:
qry += ' IDENTIFIED BY %(password)s'
args['password'] = six.text_type(password)
elif password_hash is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry += ' IDENTIFIED BY %(password)s'
else:
qry += ' IDENTIFIED BY PASSWORD %(password)s'
args['password'] = password_hash
elif salt.utils.data.is_true(allow_passwordless):
if salt.utils.data.is_true(unix_socket):
if host == 'localhost':
qry += ' IDENTIFIED VIA unix_socket'
else:
log.error(
'Auth via unix_socket can be set only for host=localhost'
)
else:
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if user_exists(user, host, password, password_hash, password_column=password_column, **connection_args):
msg = 'User \'{0}\'@\'{1}\' has been created'.format(user, host)
if not any((password, password_hash)):
msg += ' with passwordless login'
log.info(msg)
return True
log.info('User \'%s\'@\'%s\' was not created', user, host)
return False
def user_chpass(user,
host='localhost',
password=None,
password_hash=None,
allow_passwordless=False,
unix_socket=None,
password_column=None,
**connection_args):
'''
Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
compare_version = '10.2.0' if 'MariaDB' in server_version else '8.0.11'
args = {}
if password is not None:
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
password_sql = '%(password)s'
else:
password_sql = 'PASSWORD(%(password)s)'
args['password'] = password
elif password_hash is not None:
password_sql = '%(password)s'
args['password'] = password_hash
elif not salt.utils.data.is_true(allow_passwordless):
log.error('password or password_hash must be specified, unless '
'allow_passwordless=True')
return False
else:
password_sql = '\'\''
dbc = _connect(**connection_args)
if dbc is None:
return False
if not password_column:
password_column = __password_column(**connection_args)
cur = dbc.cursor()
args['user'] = user
args['host'] = host
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '=' + password_sql +
' WHERE User=%(user)s AND Host = %(host)s;')
if salt.utils.data.is_true(allow_passwordless) and \
salt.utils.data.is_true(unix_socket):
if host == 'localhost':
args['unix_socket'] = 'auth_socket'
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
qry = "ALTER USER %(user)s@%(host)s IDENTIFIED WITH %(unix_socket)s AS %(user)s;"
else:
qry = ('UPDATE mysql.user SET ' + password_column + '='
+ password_sql + ', plugin=%(unix_socket)s' +
' WHERE User=%(user)s AND Host = %(host)s;')
else:
log.error('Auth via unix_socket can be set only for host=localhost')
try:
result = _execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if salt.utils.versions.version_cmp(server_version, compare_version) >= 0:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
else:
if result:
_execute(cur, 'FLUSH PRIVILEGES;')
log.info(
'Password for user \'%s\'@\'%s\' has been %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return True
log.info(
'Password for user \'%s\'@\'%s\' was not %s',
user, host,
'changed' if any((password, password_hash)) else 'cleared'
)
return False
def user_remove(user,
host='localhost',
**connection_args):
'''
Delete MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_remove frank localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'DROP USER %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' has been removed', user, host)
return True
log.info('User \'%s\'@\'%s\' has NOT been removed', user, host)
return False
def tokenize_grant(grant):
'''
External wrapper function
:param grant:
:return: dict
CLI Example:
.. code-block:: bash
salt '*' mysql.tokenize_grant \
"GRANT SELECT, INSERT ON testdb.* TO 'testuser'@'localhost'"
'''
return _grant_to_tokens(grant)
# Maintenance
def db_check(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_check dbname
salt '*' mysql.db_check dbname dbtable
'''
ret = []
if table is None:
# we need to check all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret.append(__check_table(name, table, **connection_args))
else:
log.info('Checking table \'%s\' in db \'%s\'..', name, table)
ret = __check_table(name, table, **connection_args)
return ret
def db_repair(name,
table=None,
**connection_args):
'''
Repairs the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_repair dbname
'''
ret = []
if table is None:
# we need to repair all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret.append(__repair_table(name, table, **connection_args))
else:
log.info('Repairing table \'%s\' in db \'%s\'..', name, table)
ret = __repair_table(name, table, **connection_args)
return ret
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
# Grants
def __grant_normalize(grant):
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
grant = 'ALL PRIVILEGES'
# Grants are paste directly in SQL, must filter it
exploded_grants = grant.split(",")
for chkgrant in exploded_grants:
if chkgrant.strip().upper() not in __grants__:
raise Exception('Invalid grant : \'{0}\''.format(
chkgrant
))
return grant
def __ssl_option_sanitize(ssl_option):
new_ssl_option = []
# Like most other "salt dsl" YAML structures, ssl_option is a list of single-element dicts
for opt in ssl_option:
key = next(six.iterkeys(opt))
normal_key = key.strip().upper()
if normal_key not in __ssl_options__:
raise Exception('Invalid SSL option : \'{0}\''.format(
key
))
if normal_key in __ssl_options_parameterized__:
# SSL option parameters (cipher, issuer, subject) are pasted directly to SQL so
# we need to sanitize for single quotes...
new_ssl_option.append("{0} '{1}'".format(normal_key, opt[key].replace("'", '')))
# omit if falsey
elif opt[key]:
new_ssl_option.append(normal_key)
return ' REQUIRE ' + ' AND '.join(new_ssl_option)
def __grant_generate(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False):
'''
Validate grants and build the query that could set the given grants
Note that this query contains arguments for user and host but not for
grants or database.
'''
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
grant = __grant_normalize(grant)
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if escape:
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
dbc = quote_identifier(dbc, for_grants=(table == '*'))
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, and same thing for grants
qry = 'GRANT {0} ON {1}.{2} TO %(user)s@%(host)s'.format(grant, dbc, table)
args = {}
args['user'] = user
args['host'] = host
if ssl_option and isinstance(ssl_option, list):
qry += __ssl_option_sanitize(ssl_option)
if salt.utils.data.is_true(grant_option):
qry += ' WITH GRANT OPTION'
log.debug('Grant Query generated: %s args %s', qry, repr(args))
return {'qry': qry, 'args': args}
def user_grants(user,
host='localhost', **connection_args):
'''
Shows the grants for the given MySQL user (if it exists)
CLI Example:
.. code-block:: bash
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user, host, **connection_args):
log.info('User \'%s\'@\'%s\' does not exist', user, host)
return False
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
qry = 'SHOW GRANTS FOR %(user)s@%(host)s'
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
ret = []
results = salt.utils.data.decode(cur.fetchall())
for grant in results:
tmp = grant[0].split(' IDENTIFIED BY')[0]
if 'WITH GRANT OPTION' in grant[0] and 'WITH GRANT OPTION' not in tmp:
tmp = '{0} WITH GRANT OPTION'.format(tmp)
ret.append(tmp)
log.debug(ret)
return ret
def grant_exists(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Checks to see if a grant exists in the database
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_exists \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
server_version = salt.utils.data.decode(version(**connection_args))
if not server_version:
last_err = __context__['mysql.error']
err = 'MySQL Error: Unable to fetch current server version. Last error was: "{}"'.format(last_err)
log.error(err)
return False
if 'ALL' in grant:
if salt.utils.versions.version_cmp(server_version, '8.0') >= 0 and \
'MariaDB' not in server_version:
grant = ','.join([i for i in __all_privileges__])
else:
grant = 'ALL PRIVILEGES'
try:
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
except Exception:
log.error('Error during grant generation.')
return False
grants = user_grants(user, host, **connection_args)
if grants is False:
log.error('Grant does not exist or may not be ordered properly. In some cases, '
'this could also indicate a connection error. Check your configuration.')
return False
# Combine grants that match the same database
_grants = {}
for grant in grants:
grant_token = _grant_to_tokens(grant)
if grant_token['database'] not in _grants:
_grants[grant_token['database']] = {'user': grant_token['user'],
'database': grant_token['database'],
'host': grant_token['host'],
'grant': grant_token['grant']}
else:
_grants[grant_token['database']]['grant'].extend(grant_token['grant'])
target_tokens = _grant_to_tokens(target)
for database, grant_tokens in _grants.items():
try:
_grant_tokens = {}
_target_tokens = {}
_grant_matches = [True if i in grant_tokens['grant']
else False for i in target_tokens['grant']]
for item in ['user', 'database', 'host']:
_grant_tokens[item] = grant_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
_target_tokens[item] = target_tokens[item].replace('"', '').replace('\\', '').replace('`', '')
if _grant_tokens['user'] == _target_tokens['user'] and \
_grant_tokens['database'] == _target_tokens['database'] and \
_grant_tokens['host'] == _target_tokens['host'] and \
all(_grant_matches):
return True
else:
log.debug('grants mismatch \'%s\'<>\'%s\'', grant_tokens, target_tokens)
except Exception as exc: # Fallback to strict parsing
log.exception(exc)
if grants is not False and target in grants:
log.debug('Grant exists.')
return True
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
def grant_add(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
ssl_option=False,
**connection_args):
'''
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_add \
'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
# Avoid spaces problems
grant = grant.strip()
try:
qry = __grant_generate(grant, database, user, host, grant_option, escape, ssl_option)
except Exception:
log.error('Error during grant generation')
return False
try:
_execute(cur, qry['qry'], qry['args'])
except (MySQLdb.OperationalError, MySQLdb.ProgrammingError) as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if grant_exists(
grant, database, user, host, grant_option, escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been added',
grant, database, user
)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been added',
grant, database, user
)
return False
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
salt '*' mysql.grant_revoke \
'SELECT,INSERT,UPDATE' 'database.*' 'frank' 'localhost'
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
grant = __grant_normalize(grant)
if salt.utils.data.is_true(grant_option):
grant += ', GRANT OPTION'
db_part = database.rpartition('.')
dbc = db_part[0]
table = db_part[2]
if dbc != '*':
# _ and % are authorized on GRANT queries and should get escaped
# on the db name, but only if not requesting a table level grant
s_database = quote_identifier(dbc, for_grants=(table == '*'))
if dbc == '*':
# add revoke for *.*
# before the modification query send to mysql will looks like
# REVOKE SELECT ON `*`.* FROM %(user)s@%(host)s
s_database = dbc
if table != '*':
table = quote_identifier(table)
# identifiers cannot be used as values, same thing for grants
qry = 'REVOKE {0} ON {1}.{2} FROM %(user)s@%(host)s;'.format(
grant,
s_database,
table
)
args = {}
args['user'] = user
args['host'] = host
try:
_execute(cur, qry, args)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False
if not grant_exists(grant,
database,
user,
host,
grant_option,
escape,
**connection_args):
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has been '
'revoked', grant, database, user)
return True
log.info(
'Grant \'%s\' on \'%s\' for user \'%s\' has NOT been '
'revoked', grant, database, user)
return False
def processlist(**connection_args):
'''
Retrieves the processlist from the MySQL server via
"SHOW FULL PROCESSLIST".
Returns: a list of dicts, with each dict representing a process:
.. code-block:: python
{'Command': 'Query',
'Host': 'localhost',
'Id': 39,
'Info': 'SHOW FULL PROCESSLIST',
'Rows_examined': 0,
'Rows_read': 1,
'Rows_sent': 0,
'State': None,
'Time': 0,
'User': 'root',
'db': 'mysql'}
CLI Example:
.. code-block:: bash
salt '*' mysql.processlist
'''
ret = []
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
_execute(cur, 'SHOW FULL PROCESSLIST')
hdr = [c[0] for c in cur.description]
for _ in range(cur.rowcount):
row = cur.fetchone()
idx_r = {}
for idx_j in range(len(hdr)):
idx_r[hdr[idx_j]] = row[idx_j]
ret.append(idx_r)
cur.close()
return ret
def __do_query_into_hash(conn, sql_str):
'''
Perform the query that is passed to it (sql_str).
Returns:
results in a dict.
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--(%s)', mod, sql_str)
rtn_results = []
try:
cursor = conn.cursor()
except MySQLdb.MySQLError:
log.error('%s: Can\'t get cursor for SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
try:
_execute(cursor, sql_str)
except MySQLdb.MySQLError:
log.error('%s: try to execute : SQL->%s', mod, sql_str)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
qrs = cursor.fetchall()
for row_data in qrs:
col_cnt = 0
row = {}
for col_data in cursor.description:
col_name = col_data[0]
row[col_name] = row_data[col_cnt]
col_cnt += 1
rtn_results.append(row)
cursor.close()
log.debug('%s-->', mod)
return rtn_results
def get_master_status(**connection_args):
'''
Retrieves the master status from the minion.
Returns::
{'host.domain.com': {'Binlog_Do_DB': '',
'Binlog_Ignore_DB': '',
'File': 'mysql-bin.000021',
'Position': 107}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_master_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW MASTER STATUS")
conn.close()
# check for if this minion is not a master
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def get_slave_status(**connection_args):
'''
Retrieves the slave status from the minion.
Returns::
{'host.domain.com': {'Connect_Retry': 60,
'Exec_Master_Log_Pos': 107,
'Last_Errno': 0,
'Last_Error': '',
'Last_IO_Errno': 0,
'Last_IO_Error': '',
'Last_SQL_Errno': 0,
'Last_SQL_Error': '',
'Master_Host': 'comet.scion-eng.com',
'Master_Log_File': 'mysql-bin.000021',
'Master_Port': 3306,
'Master_SSL_Allowed': 'No',
'Master_SSL_CA_File': '',
'Master_SSL_CA_Path': '',
'Master_SSL_Cert': '',
'Master_SSL_Cipher': '',
'Master_SSL_Key': '',
'Master_SSL_Verify_Server_Cert': 'No',
'Master_Server_Id': 1,
'Master_User': 'replu',
'Read_Master_Log_Pos': 107,
'Relay_Log_File': 'klo-relay-bin.000071',
'Relay_Log_Pos': 253,
'Relay_Log_Space': 553,
'Relay_Master_Log_File': 'mysql-bin.000021',
'Replicate_Do_DB': '',
'Replicate_Do_Table': '',
'Replicate_Ignore_DB': '',
'Replicate_Ignore_Server_Ids': '',
'Replicate_Ignore_Table': '',
'Replicate_Wild_Do_Table': '',
'Replicate_Wild_Ignore_Table': '',
'Seconds_Behind_Master': 0,
'Skip_Counter': 0,
'Slave_IO_Running': 'Yes',
'Slave_IO_State': 'Waiting for master to send event',
'Slave_SQL_Running': 'Yes',
'Until_Condition': 'None',
'Until_Log_File': '',
'Until_Log_Pos': 0}}
CLI Example:
.. code-block:: bash
salt '*' mysql.get_slave_status
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW SLAVE STATUS")
conn.close()
# check for if this minion is not a slave
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv[0]
def showvariables(**connection_args):
'''
Retrieves the show variables from the minion.
Returns::
show variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showvariables
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
def showglobal(**connection_args):
'''
Retrieves the show global variables from the minion.
Returns::
show global variables full dict
CLI Example:
.. code-block:: bash
salt '*' mysql.showglobal
'''
mod = sys._getframe().f_code.co_name
log.debug('%s<--', mod)
conn = _connect(**connection_args)
if conn is None:
return []
rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES")
conn.close()
if not rtnv:
rtnv.append([])
log.debug('%s-->%s', mod, len(rtnv[0]))
return rtnv
|
saltstack/salt
|
salt/wheel/__init__.py
|
WheelClient.call_func
|
python
|
def call_func(self, fun, **kwargs):
'''
Backwards compatibility
'''
return self.low(fun, kwargs, print_event=kwargs.get('print_event', True), full_return=kwargs.get('full_return', False))
|
Backwards compatibility
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/__init__.py#L53-L57
|
[
"def low(self, fun, low, print_event=True, full_return=False):\n '''\n Execute a function from low data\n Low data includes:\n required:\n - fun: the name of the function to run\n optional:\n - arg: a list of args to pass to fun\n - kwarg: kwargs for fun\n - __user__: user who is running the command\n - __jid__: jid to run under\n - __tag__: tag to run under\n '''\n # fire the mminion loading (if not already done) here\n # this is not to clutter the output with the module loading\n # if we have a high debug level.\n self.mminion # pylint: disable=W0104\n jid = low.get('__jid__', salt.utils.jid.gen_jid(self.opts))\n tag = low.get('__tag__', salt.utils.event.tagify(jid, prefix=self.tag_prefix))\n\n data = {'fun': '{0}.{1}'.format(self.client, fun),\n 'jid': jid,\n 'user': low.get('__user__', 'UNKNOWN'),\n }\n\n event = salt.utils.event.get_event(\n 'master',\n self.opts['sock_dir'],\n self.opts['transport'],\n opts=self.opts,\n listen=False)\n\n if print_event:\n print_func = self.print_async_event \\\n if hasattr(self, 'print_async_event') \\\n else None\n else:\n # Suppress printing of return event (this keeps us from printing\n # runner/wheel output during orchestration).\n print_func = None\n\n namespaced_event = salt.utils.event.NamespacedEvent(\n event,\n tag,\n print_func=print_func\n )\n\n # TODO: test that they exist\n # TODO: Other things to inject??\n func_globals = {'__jid__': jid,\n '__user__': data['user'],\n '__tag__': tag,\n # weak ref to avoid the Exception in interpreter\n # teardown of event\n '__jid_event__': weakref.proxy(namespaced_event),\n }\n\n try:\n self_functions = pycopy.copy(self.functions)\n salt.utils.lazy.verify_fun(self_functions, fun)\n\n # Inject some useful globals to *all* the function's global\n # namespace only once per module-- not per func\n completed_funcs = []\n\n for mod_name in six.iterkeys(self_functions):\n if '.' not in mod_name:\n continue\n mod, _ = mod_name.split('.', 1)\n if mod in completed_funcs:\n continue\n completed_funcs.append(mod)\n for global_key, value in six.iteritems(func_globals):\n self.functions[mod_name].__globals__[global_key] = value\n\n # There are some discrepancies of what a \"low\" structure is in the\n # publisher world it is a dict including stuff such as jid, fun,\n # arg (a list of args, with kwargs packed in). Historically this\n # particular one has had no \"arg\" and just has had all the kwargs\n # packed into the top level object. The plan is to move away from\n # that since the caller knows what is an arg vs a kwarg, but while\n # we make the transition we will load \"kwargs\" using format_call if\n # there are no kwargs in the low object passed in.\n\n if 'arg' in low and 'kwarg' in low:\n args = low['arg']\n kwargs = low['kwarg']\n else:\n f_call = salt.utils.args.format_call(\n self.functions[fun],\n low,\n expected_extra_kws=CLIENT_INTERNAL_KEYWORDS\n )\n args = f_call.get('args', ())\n kwargs = f_call.get('kwargs', {})\n\n # Update the event data with loaded args and kwargs\n data['fun_args'] = list(args) + ([kwargs] if kwargs else [])\n func_globals['__jid_event__'].fire_event(data, 'new')\n\n # Track the job locally so we know what is running on the master\n serial = salt.payload.Serial(self.opts)\n jid_proc_file = os.path.join(*[self.opts['cachedir'], 'proc', jid])\n data['pid'] = os.getpid()\n with salt.utils.files.fopen(jid_proc_file, 'w+b') as fp_:\n fp_.write(serial.dumps(data))\n del data['pid']\n\n # Initialize a context for executing the method.\n with tornado.stack_context.StackContext(self.functions.context_dict.clone):\n func = self.functions[fun]\n try:\n data['return'] = func(*args, **kwargs)\n except TypeError as exc:\n data['return'] = salt.utils.text.cli_info('Error: {exc}\\nUsage:\\n{doc}'.format(\n exc=exc, doc=func.__doc__), 'Passed invalid arguments')\n except Exception as exc:\n data['return'] = salt.utils.text.cli_info(six.text_type(exc), 'General error occurred')\n try:\n data['success'] = self.context.get('retcode', 0) == 0\n except AttributeError:\n # Assume a True result if no context attribute\n data['success'] = True\n if isinstance(data['return'], dict) and 'data' in data['return']:\n # some functions can return boolean values\n data['success'] = salt.utils.state.check_result(data['return']['data'])\n except (Exception, SystemExit) as ex:\n if isinstance(ex, salt.exceptions.NotImplemented):\n data['return'] = six.text_type(ex)\n else:\n data['return'] = 'Exception occurred in {client} {fun}: {tb}'.format(\n client=self.client, fun=fun, tb=traceback.format_exc())\n data['success'] = False\n finally:\n # Job has finished or issue found, so let's clean up after ourselves\n try:\n os.remove(jid_proc_file)\n except OSError as err:\n log.error(\"Error attempting to remove master job tracker: %s\", err)\n\n if self.store_job:\n try:\n salt.utils.job.store_job(\n self.opts,\n {\n 'id': self.opts['id'],\n 'tgt': self.opts['id'],\n 'jid': data['jid'],\n 'return': data,\n },\n event=None,\n mminion=self.mminion,\n )\n except salt.exceptions.SaltCacheError:\n log.error('Could not store job cache info. '\n 'Job details for this run may be unavailable.')\n\n # Outputters _can_ mutate data so write to the job cache first!\n namespaced_event.fire_event(data, 'ret')\n\n # if we fired an event, make sure to delete the event object.\n # This will ensure that we call destroy, which will do the 0MQ linger\n log.info('Runner completed: %s', data['jid'])\n del event\n del namespaced_event\n return data if full_return else data['return']\n"
] |
class WheelClient(salt.client.mixins.SyncClientMixin,
salt.client.mixins.AsyncClientMixin, object):
'''
An interface to Salt's wheel modules
:ref:`Wheel modules <all-salt.wheel>` interact with various parts of the
Salt Master.
Importing and using ``WheelClient`` must be done on the same machine as the
Salt Master and it must be done using the same user that the Salt Master is
running as. Unless :conf_master:`external_auth` is configured and the user
is authorized to execute wheel functions: (``@wheel``).
Usage:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
'''
client = 'wheel'
tag_prefix = 'wheel'
def __init__(self, opts=None):
self.opts = opts
self.context = {}
self.functions = salt.loader.wheels(opts, context=self.context)
# TODO: remove/deprecate
# TODO: Inconsistent with runner client-- the runner client's master_call gives
# an asynchronous return, unlike this
def master_call(self, **kwargs):
'''
Execute a wheel function through the master network interface (eauth).
'''
load = kwargs
load['cmd'] = 'wheel'
interface = self.opts['interface']
if interface == '0.0.0.0':
interface = '127.0.0.1'
master_uri = 'tcp://{}:{}'.format(
salt.utils.zeromq.ip_bracket(interface),
six.text_type(self.opts['ret_port'])
)
channel = salt.transport.client.ReqChannel.factory(self.opts,
crypt='clear',
master_uri=master_uri,
usage='master_call')
try:
ret = channel.send(load)
finally:
channel.close()
if isinstance(ret, collections.Mapping):
if 'error' in ret:
salt.utils.error.raise_error(**ret['error'])
return ret
def cmd_sync(self, low, timeout=None, full_return=False):
'''
Execute a wheel function synchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized to execute runner functions: (``@wheel``).
.. code-block:: python
>>> wheel.cmd_sync({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
return self.master_call(**low)
# TODO: Inconsistent with runner client-- that one uses the master_call function
# and runs within the master daemon. Need to pick one...
def cmd_async(self, low):
'''
Execute a function asynchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized
.. code-block:: python
>>> wheel.cmd_async({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}
'''
fun = low.pop('fun')
return self.asynchronous(fun, low)
def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):
'''
Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
return super(WheelClient, self).cmd(fun,
arg,
pub_data,
kwarg,
print_event,
full_return)
|
saltstack/salt
|
salt/wheel/__init__.py
|
WheelClient.master_call
|
python
|
def master_call(self, **kwargs):
'''
Execute a wheel function through the master network interface (eauth).
'''
load = kwargs
load['cmd'] = 'wheel'
interface = self.opts['interface']
if interface == '0.0.0.0':
interface = '127.0.0.1'
master_uri = 'tcp://{}:{}'.format(
salt.utils.zeromq.ip_bracket(interface),
six.text_type(self.opts['ret_port'])
)
channel = salt.transport.client.ReqChannel.factory(self.opts,
crypt='clear',
master_uri=master_uri,
usage='master_call')
try:
ret = channel.send(load)
finally:
channel.close()
if isinstance(ret, collections.Mapping):
if 'error' in ret:
salt.utils.error.raise_error(**ret['error'])
return ret
|
Execute a wheel function through the master network interface (eauth).
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/__init__.py#L61-L85
|
[
"def ip_bracket(addr):\n '''\n Convert IP address representation to ZMQ (URL) format. ZMQ expects\n brackets around IPv6 literals, since they are used in URLs.\n '''\n addr = ipaddress.ip_address(addr)\n return ('[{}]' if addr.version == 6 else '{}').format(addr)\n",
"def factory(opts, **kwargs):\n # All Sync interfaces are just wrappers around the Async ones\n sync = SyncWrapper(AsyncReqChannel.factory, (opts,), kwargs)\n return sync\n"
] |
class WheelClient(salt.client.mixins.SyncClientMixin,
salt.client.mixins.AsyncClientMixin, object):
'''
An interface to Salt's wheel modules
:ref:`Wheel modules <all-salt.wheel>` interact with various parts of the
Salt Master.
Importing and using ``WheelClient`` must be done on the same machine as the
Salt Master and it must be done using the same user that the Salt Master is
running as. Unless :conf_master:`external_auth` is configured and the user
is authorized to execute wheel functions: (``@wheel``).
Usage:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
'''
client = 'wheel'
tag_prefix = 'wheel'
def __init__(self, opts=None):
self.opts = opts
self.context = {}
self.functions = salt.loader.wheels(opts, context=self.context)
# TODO: remove/deprecate
def call_func(self, fun, **kwargs):
'''
Backwards compatibility
'''
return self.low(fun, kwargs, print_event=kwargs.get('print_event', True), full_return=kwargs.get('full_return', False))
# TODO: Inconsistent with runner client-- the runner client's master_call gives
# an asynchronous return, unlike this
def cmd_sync(self, low, timeout=None, full_return=False):
'''
Execute a wheel function synchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized to execute runner functions: (``@wheel``).
.. code-block:: python
>>> wheel.cmd_sync({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
return self.master_call(**low)
# TODO: Inconsistent with runner client-- that one uses the master_call function
# and runs within the master daemon. Need to pick one...
def cmd_async(self, low):
'''
Execute a function asynchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized
.. code-block:: python
>>> wheel.cmd_async({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}
'''
fun = low.pop('fun')
return self.asynchronous(fun, low)
def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):
'''
Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
return super(WheelClient, self).cmd(fun,
arg,
pub_data,
kwarg,
print_event,
full_return)
|
saltstack/salt
|
salt/wheel/__init__.py
|
WheelClient.cmd_async
|
python
|
def cmd_async(self, low):
'''
Execute a function asynchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized
.. code-block:: python
>>> wheel.cmd_async({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}
'''
fun = low.pop('fun')
return self.asynchronous(fun, low)
|
Execute a function asynchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized
.. code-block:: python
>>> wheel.cmd_async({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/__init__.py#L109-L128
|
[
"def asynchronous(self, fun, low, user='UNKNOWN', pub=None):\n '''\n Execute the function in a multiprocess and return the event tag to use\n to watch for the return\n '''\n async_pub = pub if pub is not None else self._gen_async_pub()\n\n proc = salt.utils.process.SignalHandlingMultiprocessingProcess(\n target=self._proc_function,\n args=(fun, low, user, async_pub['tag'], async_pub['jid']))\n with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):\n # Reset current signals before starting the process in\n # order not to inherit the current signal handlers\n proc.start()\n proc.join() # MUST join, otherwise we leave zombies all over\n return async_pub\n"
] |
class WheelClient(salt.client.mixins.SyncClientMixin,
salt.client.mixins.AsyncClientMixin, object):
'''
An interface to Salt's wheel modules
:ref:`Wheel modules <all-salt.wheel>` interact with various parts of the
Salt Master.
Importing and using ``WheelClient`` must be done on the same machine as the
Salt Master and it must be done using the same user that the Salt Master is
running as. Unless :conf_master:`external_auth` is configured and the user
is authorized to execute wheel functions: (``@wheel``).
Usage:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
'''
client = 'wheel'
tag_prefix = 'wheel'
def __init__(self, opts=None):
self.opts = opts
self.context = {}
self.functions = salt.loader.wheels(opts, context=self.context)
# TODO: remove/deprecate
def call_func(self, fun, **kwargs):
'''
Backwards compatibility
'''
return self.low(fun, kwargs, print_event=kwargs.get('print_event', True), full_return=kwargs.get('full_return', False))
# TODO: Inconsistent with runner client-- the runner client's master_call gives
# an asynchronous return, unlike this
def master_call(self, **kwargs):
'''
Execute a wheel function through the master network interface (eauth).
'''
load = kwargs
load['cmd'] = 'wheel'
interface = self.opts['interface']
if interface == '0.0.0.0':
interface = '127.0.0.1'
master_uri = 'tcp://{}:{}'.format(
salt.utils.zeromq.ip_bracket(interface),
six.text_type(self.opts['ret_port'])
)
channel = salt.transport.client.ReqChannel.factory(self.opts,
crypt='clear',
master_uri=master_uri,
usage='master_call')
try:
ret = channel.send(load)
finally:
channel.close()
if isinstance(ret, collections.Mapping):
if 'error' in ret:
salt.utils.error.raise_error(**ret['error'])
return ret
def cmd_sync(self, low, timeout=None, full_return=False):
'''
Execute a wheel function synchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized to execute runner functions: (``@wheel``).
.. code-block:: python
>>> wheel.cmd_sync({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
return self.master_call(**low)
# TODO: Inconsistent with runner client-- that one uses the master_call function
# and runs within the master daemon. Need to pick one...
def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):
'''
Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
return super(WheelClient, self).cmd(fun,
arg,
pub_data,
kwarg,
print_event,
full_return)
|
saltstack/salt
|
salt/wheel/__init__.py
|
WheelClient.cmd
|
python
|
def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):
'''
Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
return super(WheelClient, self).cmd(fun,
arg,
pub_data,
kwarg,
print_event,
full_return)
|
Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/__init__.py#L130-L144
|
[
"def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):\n '''\n Execute a function\n\n .. code-block:: python\n\n >>> opts = salt.config.master_config('/etc/salt/master')\n >>> runner = salt.runner.RunnerClient(opts)\n >>> runner.cmd('jobs.list_jobs', [])\n {\n '20131219215650131543': {\n 'Arguments': [300],\n 'Function': 'test.sleep',\n 'StartTime': '2013, Dec 19 21:56:50.131543',\n 'Target': '*',\n 'Target-type': 'glob',\n 'User': 'saltdev'\n },\n '20131219215921857715': {\n 'Arguments': [300],\n 'Function': 'test.sleep',\n 'StartTime': '2013, Dec 19 21:59:21.857715',\n 'Target': '*',\n 'Target-type': 'glob',\n 'User': 'saltdev'\n },\n }\n\n '''\n if arg is None:\n arg = tuple()\n if not isinstance(arg, list) and not isinstance(arg, tuple):\n raise salt.exceptions.SaltInvocationError(\n 'arg must be formatted as a list/tuple'\n )\n if pub_data is None:\n pub_data = {}\n if not isinstance(pub_data, dict):\n raise salt.exceptions.SaltInvocationError(\n 'pub_data must be formatted as a dictionary'\n )\n if kwarg is None:\n kwarg = {}\n if not isinstance(kwarg, dict):\n raise salt.exceptions.SaltInvocationError(\n 'kwarg must be formatted as a dictionary'\n )\n arglist = salt.utils.args.parse_input(\n arg,\n no_parse=self.opts.get('no_parse', []))\n\n # if you were passed kwarg, add it to arglist\n if kwarg:\n kwarg['__kwarg__'] = True\n arglist.append(kwarg)\n\n args, kwargs = salt.minion.load_args_and_kwargs(\n self.functions[fun], arglist, pub_data\n )\n low = {'fun': fun,\n 'arg': args,\n 'kwarg': kwargs}\n return self.low(fun, low, print_event=print_event, full_return=full_return)\n"
] |
class WheelClient(salt.client.mixins.SyncClientMixin,
salt.client.mixins.AsyncClientMixin, object):
'''
An interface to Salt's wheel modules
:ref:`Wheel modules <all-salt.wheel>` interact with various parts of the
Salt Master.
Importing and using ``WheelClient`` must be done on the same machine as the
Salt Master and it must be done using the same user that the Salt Master is
running as. Unless :conf_master:`external_auth` is configured and the user
is authorized to execute wheel functions: (``@wheel``).
Usage:
.. code-block:: python
import salt.config
import salt.wheel
opts = salt.config.master_config('/etc/salt/master')
wheel = salt.wheel.WheelClient(opts)
'''
client = 'wheel'
tag_prefix = 'wheel'
def __init__(self, opts=None):
self.opts = opts
self.context = {}
self.functions = salt.loader.wheels(opts, context=self.context)
# TODO: remove/deprecate
def call_func(self, fun, **kwargs):
'''
Backwards compatibility
'''
return self.low(fun, kwargs, print_event=kwargs.get('print_event', True), full_return=kwargs.get('full_return', False))
# TODO: Inconsistent with runner client-- the runner client's master_call gives
# an asynchronous return, unlike this
def master_call(self, **kwargs):
'''
Execute a wheel function through the master network interface (eauth).
'''
load = kwargs
load['cmd'] = 'wheel'
interface = self.opts['interface']
if interface == '0.0.0.0':
interface = '127.0.0.1'
master_uri = 'tcp://{}:{}'.format(
salt.utils.zeromq.ip_bracket(interface),
six.text_type(self.opts['ret_port'])
)
channel = salt.transport.client.ReqChannel.factory(self.opts,
crypt='clear',
master_uri=master_uri,
usage='master_call')
try:
ret = channel.send(load)
finally:
channel.close()
if isinstance(ret, collections.Mapping):
if 'error' in ret:
salt.utils.error.raise_error(**ret['error'])
return ret
def cmd_sync(self, low, timeout=None, full_return=False):
'''
Execute a wheel function synchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized to execute runner functions: (``@wheel``).
.. code-block:: python
>>> wheel.cmd_sync({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
return self.master_call(**low)
# TODO: Inconsistent with runner client-- that one uses the master_call function
# and runs within the master daemon. Need to pick one...
def cmd_async(self, low):
'''
Execute a function asynchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized
.. code-block:: python
>>> wheel.cmd_async({
'fun': 'key.finger',
'match': 'jerry',
'eauth': 'auto',
'username': 'saltdev',
'password': 'saltdev',
})
{'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}
'''
fun = low.pop('fun')
return self.asynchronous(fun, low)
|
saltstack/salt
|
salt/modules/makeconf.py
|
_add_var
|
python
|
def _add_var(var, value):
'''
Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line.
'''
makeconf = _get_makeconf()
layman = 'source /var/lib/layman/make.conf'
fullvar = '{0}="{1}"'.format(var, value)
if __salt__['file.contains'](makeconf, layman):
# TODO perhaps make this a function in the file module?
cmd = ['sed', '-i', r'/{0}/ i\{1}'.format(
layman.replace('/', '\\/'),
fullvar),
makeconf]
__salt__['cmd.run'](cmd)
else:
__salt__['file.append'](makeconf, fullvar)
|
Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/makeconf.py#L36-L54
|
[
"def _get_makeconf():\n '''\n Find the correct make.conf. Gentoo recently moved the make.conf\n but still supports the old location, using the old location first\n '''\n old_conf = '/etc/make.conf'\n new_conf = '/etc/portage/make.conf'\n if __salt__['file.file_exists'](old_conf):\n return old_conf\n elif __salt__['file.file_exists'](new_conf):\n return new_conf\n"
] |
# -*- coding: utf-8 -*-
'''
Support for modifying make.conf under Gentoo
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.data
import salt.utils.files
def __virtual__():
'''
Only work on Gentoo
'''
if __grains__['os_family'] == 'Gentoo':
return 'makeconf'
return (False, 'The makeconf execution module cannot be loaded: only available on Gentoo systems.')
def _get_makeconf():
'''
Find the correct make.conf. Gentoo recently moved the make.conf
but still supports the old location, using the old location first
'''
old_conf = '/etc/make.conf'
new_conf = '/etc/portage/make.conf'
if __salt__['file.file_exists'](old_conf):
return old_conf
elif __salt__['file.file_exists'](new_conf):
return new_conf
def set_var(var, value):
'''
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, replace its value
if old_value is not None:
__salt__['file.sed'](
makeconf, '^{0}=.*'.format(var), '{0}="{1}"'.format(var, value)
)
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def remove_var(var):
'''
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var is in file
if old_value is not None:
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var), '')
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def append_var(var, value):
'''
Add to or create a new variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, add to its value
if old_value is not None:
appended_value = '{0} {1}'.format(old_value, value)
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var),
'{0}="{1}"'.format(var, appended_value))
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def trim_var(var, value):
'''
Remove a value from a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var in file, trim value from its value
if old_value is not None:
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def get_var(var):
'''
Get the value of a variable in make.conf
Return the value of the variable or None if the variable is not in
make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_var 'LINGUAS'
'''
makeconf = _get_makeconf()
# Open makeconf
with salt.utils.files.fopen(makeconf) as fn_:
conf_file = salt.utils.data.decode(fn_.readlines())
for line in conf_file:
if line.startswith(var):
ret = line.split('=', 1)[1]
if '"' in ret:
ret = ret.split('"')[1]
elif '#' in ret:
ret = ret.split('#')[0]
ret = ret.strip()
return ret
return None
def var_contains(var, value):
'''
Verify if variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.var_contains 'LINGUAS' 'en'
'''
setval = get_var(var)
# Remove any escaping that was needed to past through salt
value = value.replace('\\', '')
if setval is None:
return False
return value in setval.split()
def set_cflags(value):
'''
Set the CFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cflags '-march=native -O2 -pipe'
'''
return set_var('CFLAGS', value)
def get_cflags():
'''
Get the value of CFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cflags
'''
return get_var('CFLAGS')
def append_cflags(value):
'''
Add to or create a new CFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cflags '-pipe'
'''
return append_var('CFLAGS', value)
def trim_cflags(value):
'''
Remove a value from CFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cflags '-pipe'
'''
return trim_var('CFLAGS', value)
def cflags_contains(value):
'''
Verify if CFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cflags_contains '-pipe'
'''
return var_contains('CFLAGS', value)
def set_cxxflags(value):
'''
Set the CXXFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cxxflags '-march=native -O2 -pipe'
'''
return set_var('CXXFLAGS', value)
def get_cxxflags():
'''
Get the value of CXXFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cxxflags
'''
return get_var('CXXFLAGS')
def append_cxxflags(value):
'''
Add to or create a new CXXFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cxxflags '-pipe'
'''
return append_var('CXXFLAGS', value)
def trim_cxxflags(value):
'''
Remove a value from CXXFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cxxflags '-pipe'
'''
return trim_var('CXXFLAGS', value)
def cxxflags_contains(value):
'''
Verify if CXXFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cxxflags_contains '-pipe'
'''
return var_contains('CXXFLAGS', value)
def set_chost(value):
'''
Set the CHOST variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_chost 'x86_64-pc-linux-gnu'
'''
return set_var('CHOST', value)
def get_chost():
'''
Get the value of CHOST variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_chost
'''
return get_var('CHOST')
def chost_contains(value):
'''
Verify if CHOST variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.chost_contains 'x86_64-pc-linux-gnu'
'''
return var_contains('CHOST', value)
def set_makeopts(value):
'''
Set the MAKEOPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_makeopts '-j3'
'''
return set_var('MAKEOPTS', value)
def get_makeopts():
'''
Get the value of MAKEOPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_makeopts
'''
return get_var('MAKEOPTS')
def append_makeopts(value):
'''
Add to or create a new MAKEOPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_makeopts '-j3'
'''
return append_var('MAKEOPTS', value)
def trim_makeopts(value):
'''
Remove a value from MAKEOPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_makeopts '-j3'
'''
return trim_var('MAKEOPTS', value)
def makeopts_contains(value):
'''
Verify if MAKEOPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.makeopts_contains '-j3'
'''
return var_contains('MAKEOPTS', value)
def set_emerge_default_opts(value):
'''
Set the EMERGE_DEFAULT_OPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_emerge_default_opts '--jobs'
'''
return set_var('EMERGE_DEFAULT_OPTS', value)
def get_emerge_default_opts():
'''
Get the value of EMERGE_DEFAULT_OPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_emerge_default_opts
'''
return get_var('EMERGE_DEFAULT_OPTS')
def append_emerge_default_opts(value):
'''
Add to or create a new EMERGE_DEFAULT_OPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_emerge_default_opts '--jobs'
'''
return append_var('EMERGE_DEFAULT_OPTS', value)
def trim_emerge_default_opts(value):
'''
Remove a value from EMERGE_DEFAULT_OPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_emerge_default_opts '--jobs'
'''
return trim_var('EMERGE_DEFAULT_OPTS', value)
def emerge_default_opts_contains(value):
'''
Verify if EMERGE_DEFAULT_OPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.emerge_default_opts_contains '--jobs'
'''
return var_contains('EMERGE_DEFAULT_OPTS', value)
def set_gentoo_mirrors(value):
'''
Set the GENTOO_MIRRORS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return set_var('GENTOO_MIRRORS', value)
def get_gentoo_mirrors():
'''
Get the value of GENTOO_MIRRORS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_gentoo_mirrors
'''
return get_var('GENTOO_MIRRORS')
def append_gentoo_mirrors(value):
'''
Add to or create a new GENTOO_MIRRORS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return append_var('GENTOO_MIRRORS', value)
def trim_gentoo_mirrors(value):
'''
Remove a value from GENTOO_MIRRORS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return trim_var('GENTOO_MIRRORS', value)
def gentoo_mirrors_contains(value):
'''
Verify if GENTOO_MIRRORS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.gentoo_mirrors_contains 'http://distfiles.gentoo.org'
'''
return var_contains('GENTOO_MIRRORS', value)
def set_sync(value):
'''
Set the SYNC variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_sync 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return set_var('SYNC', value)
def get_sync():
'''
Get the value of SYNC variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_sync
'''
return get_var('SYNC')
def sync_contains(value):
'''
Verify if SYNC variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.sync_contains 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return var_contains('SYNC', value)
def get_features():
'''
Get the value of FEATURES variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_features
'''
return get_var('FEATURES')
def append_features(value):
'''
Add to or create a new FEATURES in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_features 'webrsync-gpg'
'''
return append_var('FEATURES', value)
def trim_features(value):
'''
Remove a value from FEATURES variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_features 'webrsync-gpg'
'''
return trim_var('FEATURES', value)
def features_contains(value):
'''
Verify if FEATURES variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.features_contains 'webrsync-gpg'
'''
return var_contains('FEATURES', value)
|
saltstack/salt
|
salt/modules/makeconf.py
|
set_var
|
python
|
def set_var(var, value):
'''
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, replace its value
if old_value is not None:
__salt__['file.sed'](
makeconf, '^{0}=.*'.format(var), '{0}="{1}"'.format(var, value)
)
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
|
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/makeconf.py#L57-L85
|
[
"def _get_makeconf():\n '''\n Find the correct make.conf. Gentoo recently moved the make.conf\n but still supports the old location, using the old location first\n '''\n old_conf = '/etc/make.conf'\n new_conf = '/etc/portage/make.conf'\n if __salt__['file.file_exists'](old_conf):\n return old_conf\n elif __salt__['file.file_exists'](new_conf):\n return new_conf\n",
"def _add_var(var, value):\n '''\n Add a new var to the make.conf. If using layman, the source line\n for the layman make.conf needs to be at the very end of the\n config. This ensures that the new var will be above the source\n line.\n '''\n makeconf = _get_makeconf()\n layman = 'source /var/lib/layman/make.conf'\n fullvar = '{0}=\"{1}\"'.format(var, value)\n if __salt__['file.contains'](makeconf, layman):\n # TODO perhaps make this a function in the file module?\n cmd = ['sed', '-i', r'/{0}/ i\\{1}'.format(\n layman.replace('/', '\\\\/'),\n fullvar),\n makeconf]\n __salt__['cmd.run'](cmd)\n else:\n __salt__['file.append'](makeconf, fullvar)\n",
"def get_var(var):\n '''\n Get the value of a variable in make.conf\n\n Return the value of the variable or None if the variable is not in\n make.conf\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' makeconf.get_var 'LINGUAS'\n '''\n makeconf = _get_makeconf()\n # Open makeconf\n with salt.utils.files.fopen(makeconf) as fn_:\n conf_file = salt.utils.data.decode(fn_.readlines())\n for line in conf_file:\n if line.startswith(var):\n ret = line.split('=', 1)[1]\n if '\"' in ret:\n ret = ret.split('\"')[1]\n elif '#' in ret:\n ret = ret.split('#')[0]\n ret = ret.strip()\n return ret\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Support for modifying make.conf under Gentoo
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.data
import salt.utils.files
def __virtual__():
'''
Only work on Gentoo
'''
if __grains__['os_family'] == 'Gentoo':
return 'makeconf'
return (False, 'The makeconf execution module cannot be loaded: only available on Gentoo systems.')
def _get_makeconf():
'''
Find the correct make.conf. Gentoo recently moved the make.conf
but still supports the old location, using the old location first
'''
old_conf = '/etc/make.conf'
new_conf = '/etc/portage/make.conf'
if __salt__['file.file_exists'](old_conf):
return old_conf
elif __salt__['file.file_exists'](new_conf):
return new_conf
def _add_var(var, value):
'''
Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line.
'''
makeconf = _get_makeconf()
layman = 'source /var/lib/layman/make.conf'
fullvar = '{0}="{1}"'.format(var, value)
if __salt__['file.contains'](makeconf, layman):
# TODO perhaps make this a function in the file module?
cmd = ['sed', '-i', r'/{0}/ i\{1}'.format(
layman.replace('/', '\\/'),
fullvar),
makeconf]
__salt__['cmd.run'](cmd)
else:
__salt__['file.append'](makeconf, fullvar)
def remove_var(var):
'''
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var is in file
if old_value is not None:
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var), '')
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def append_var(var, value):
'''
Add to or create a new variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, add to its value
if old_value is not None:
appended_value = '{0} {1}'.format(old_value, value)
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var),
'{0}="{1}"'.format(var, appended_value))
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def trim_var(var, value):
'''
Remove a value from a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var in file, trim value from its value
if old_value is not None:
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def get_var(var):
'''
Get the value of a variable in make.conf
Return the value of the variable or None if the variable is not in
make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_var 'LINGUAS'
'''
makeconf = _get_makeconf()
# Open makeconf
with salt.utils.files.fopen(makeconf) as fn_:
conf_file = salt.utils.data.decode(fn_.readlines())
for line in conf_file:
if line.startswith(var):
ret = line.split('=', 1)[1]
if '"' in ret:
ret = ret.split('"')[1]
elif '#' in ret:
ret = ret.split('#')[0]
ret = ret.strip()
return ret
return None
def var_contains(var, value):
'''
Verify if variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.var_contains 'LINGUAS' 'en'
'''
setval = get_var(var)
# Remove any escaping that was needed to past through salt
value = value.replace('\\', '')
if setval is None:
return False
return value in setval.split()
def set_cflags(value):
'''
Set the CFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cflags '-march=native -O2 -pipe'
'''
return set_var('CFLAGS', value)
def get_cflags():
'''
Get the value of CFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cflags
'''
return get_var('CFLAGS')
def append_cflags(value):
'''
Add to or create a new CFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cflags '-pipe'
'''
return append_var('CFLAGS', value)
def trim_cflags(value):
'''
Remove a value from CFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cflags '-pipe'
'''
return trim_var('CFLAGS', value)
def cflags_contains(value):
'''
Verify if CFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cflags_contains '-pipe'
'''
return var_contains('CFLAGS', value)
def set_cxxflags(value):
'''
Set the CXXFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cxxflags '-march=native -O2 -pipe'
'''
return set_var('CXXFLAGS', value)
def get_cxxflags():
'''
Get the value of CXXFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cxxflags
'''
return get_var('CXXFLAGS')
def append_cxxflags(value):
'''
Add to or create a new CXXFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cxxflags '-pipe'
'''
return append_var('CXXFLAGS', value)
def trim_cxxflags(value):
'''
Remove a value from CXXFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cxxflags '-pipe'
'''
return trim_var('CXXFLAGS', value)
def cxxflags_contains(value):
'''
Verify if CXXFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cxxflags_contains '-pipe'
'''
return var_contains('CXXFLAGS', value)
def set_chost(value):
'''
Set the CHOST variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_chost 'x86_64-pc-linux-gnu'
'''
return set_var('CHOST', value)
def get_chost():
'''
Get the value of CHOST variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_chost
'''
return get_var('CHOST')
def chost_contains(value):
'''
Verify if CHOST variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.chost_contains 'x86_64-pc-linux-gnu'
'''
return var_contains('CHOST', value)
def set_makeopts(value):
'''
Set the MAKEOPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_makeopts '-j3'
'''
return set_var('MAKEOPTS', value)
def get_makeopts():
'''
Get the value of MAKEOPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_makeopts
'''
return get_var('MAKEOPTS')
def append_makeopts(value):
'''
Add to or create a new MAKEOPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_makeopts '-j3'
'''
return append_var('MAKEOPTS', value)
def trim_makeopts(value):
'''
Remove a value from MAKEOPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_makeopts '-j3'
'''
return trim_var('MAKEOPTS', value)
def makeopts_contains(value):
'''
Verify if MAKEOPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.makeopts_contains '-j3'
'''
return var_contains('MAKEOPTS', value)
def set_emerge_default_opts(value):
'''
Set the EMERGE_DEFAULT_OPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_emerge_default_opts '--jobs'
'''
return set_var('EMERGE_DEFAULT_OPTS', value)
def get_emerge_default_opts():
'''
Get the value of EMERGE_DEFAULT_OPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_emerge_default_opts
'''
return get_var('EMERGE_DEFAULT_OPTS')
def append_emerge_default_opts(value):
'''
Add to or create a new EMERGE_DEFAULT_OPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_emerge_default_opts '--jobs'
'''
return append_var('EMERGE_DEFAULT_OPTS', value)
def trim_emerge_default_opts(value):
'''
Remove a value from EMERGE_DEFAULT_OPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_emerge_default_opts '--jobs'
'''
return trim_var('EMERGE_DEFAULT_OPTS', value)
def emerge_default_opts_contains(value):
'''
Verify if EMERGE_DEFAULT_OPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.emerge_default_opts_contains '--jobs'
'''
return var_contains('EMERGE_DEFAULT_OPTS', value)
def set_gentoo_mirrors(value):
'''
Set the GENTOO_MIRRORS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return set_var('GENTOO_MIRRORS', value)
def get_gentoo_mirrors():
'''
Get the value of GENTOO_MIRRORS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_gentoo_mirrors
'''
return get_var('GENTOO_MIRRORS')
def append_gentoo_mirrors(value):
'''
Add to or create a new GENTOO_MIRRORS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return append_var('GENTOO_MIRRORS', value)
def trim_gentoo_mirrors(value):
'''
Remove a value from GENTOO_MIRRORS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return trim_var('GENTOO_MIRRORS', value)
def gentoo_mirrors_contains(value):
'''
Verify if GENTOO_MIRRORS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.gentoo_mirrors_contains 'http://distfiles.gentoo.org'
'''
return var_contains('GENTOO_MIRRORS', value)
def set_sync(value):
'''
Set the SYNC variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_sync 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return set_var('SYNC', value)
def get_sync():
'''
Get the value of SYNC variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_sync
'''
return get_var('SYNC')
def sync_contains(value):
'''
Verify if SYNC variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.sync_contains 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return var_contains('SYNC', value)
def get_features():
'''
Get the value of FEATURES variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_features
'''
return get_var('FEATURES')
def append_features(value):
'''
Add to or create a new FEATURES in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_features 'webrsync-gpg'
'''
return append_var('FEATURES', value)
def trim_features(value):
'''
Remove a value from FEATURES variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_features 'webrsync-gpg'
'''
return trim_var('FEATURES', value)
def features_contains(value):
'''
Verify if FEATURES variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.features_contains 'webrsync-gpg'
'''
return var_contains('FEATURES', value)
|
saltstack/salt
|
salt/modules/makeconf.py
|
remove_var
|
python
|
def remove_var(var):
'''
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var is in file
if old_value is not None:
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var), '')
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
|
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/makeconf.py#L88-L112
|
[
"def _get_makeconf():\n '''\n Find the correct make.conf. Gentoo recently moved the make.conf\n but still supports the old location, using the old location first\n '''\n old_conf = '/etc/make.conf'\n new_conf = '/etc/portage/make.conf'\n if __salt__['file.file_exists'](old_conf):\n return old_conf\n elif __salt__['file.file_exists'](new_conf):\n return new_conf\n",
"def get_var(var):\n '''\n Get the value of a variable in make.conf\n\n Return the value of the variable or None if the variable is not in\n make.conf\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' makeconf.get_var 'LINGUAS'\n '''\n makeconf = _get_makeconf()\n # Open makeconf\n with salt.utils.files.fopen(makeconf) as fn_:\n conf_file = salt.utils.data.decode(fn_.readlines())\n for line in conf_file:\n if line.startswith(var):\n ret = line.split('=', 1)[1]\n if '\"' in ret:\n ret = ret.split('\"')[1]\n elif '#' in ret:\n ret = ret.split('#')[0]\n ret = ret.strip()\n return ret\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Support for modifying make.conf under Gentoo
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.data
import salt.utils.files
def __virtual__():
'''
Only work on Gentoo
'''
if __grains__['os_family'] == 'Gentoo':
return 'makeconf'
return (False, 'The makeconf execution module cannot be loaded: only available on Gentoo systems.')
def _get_makeconf():
'''
Find the correct make.conf. Gentoo recently moved the make.conf
but still supports the old location, using the old location first
'''
old_conf = '/etc/make.conf'
new_conf = '/etc/portage/make.conf'
if __salt__['file.file_exists'](old_conf):
return old_conf
elif __salt__['file.file_exists'](new_conf):
return new_conf
def _add_var(var, value):
'''
Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line.
'''
makeconf = _get_makeconf()
layman = 'source /var/lib/layman/make.conf'
fullvar = '{0}="{1}"'.format(var, value)
if __salt__['file.contains'](makeconf, layman):
# TODO perhaps make this a function in the file module?
cmd = ['sed', '-i', r'/{0}/ i\{1}'.format(
layman.replace('/', '\\/'),
fullvar),
makeconf]
__salt__['cmd.run'](cmd)
else:
__salt__['file.append'](makeconf, fullvar)
def set_var(var, value):
'''
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, replace its value
if old_value is not None:
__salt__['file.sed'](
makeconf, '^{0}=.*'.format(var), '{0}="{1}"'.format(var, value)
)
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def append_var(var, value):
'''
Add to or create a new variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, add to its value
if old_value is not None:
appended_value = '{0} {1}'.format(old_value, value)
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var),
'{0}="{1}"'.format(var, appended_value))
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def trim_var(var, value):
'''
Remove a value from a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var in file, trim value from its value
if old_value is not None:
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def get_var(var):
'''
Get the value of a variable in make.conf
Return the value of the variable or None if the variable is not in
make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_var 'LINGUAS'
'''
makeconf = _get_makeconf()
# Open makeconf
with salt.utils.files.fopen(makeconf) as fn_:
conf_file = salt.utils.data.decode(fn_.readlines())
for line in conf_file:
if line.startswith(var):
ret = line.split('=', 1)[1]
if '"' in ret:
ret = ret.split('"')[1]
elif '#' in ret:
ret = ret.split('#')[0]
ret = ret.strip()
return ret
return None
def var_contains(var, value):
'''
Verify if variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.var_contains 'LINGUAS' 'en'
'''
setval = get_var(var)
# Remove any escaping that was needed to past through salt
value = value.replace('\\', '')
if setval is None:
return False
return value in setval.split()
def set_cflags(value):
'''
Set the CFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cflags '-march=native -O2 -pipe'
'''
return set_var('CFLAGS', value)
def get_cflags():
'''
Get the value of CFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cflags
'''
return get_var('CFLAGS')
def append_cflags(value):
'''
Add to or create a new CFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cflags '-pipe'
'''
return append_var('CFLAGS', value)
def trim_cflags(value):
'''
Remove a value from CFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cflags '-pipe'
'''
return trim_var('CFLAGS', value)
def cflags_contains(value):
'''
Verify if CFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cflags_contains '-pipe'
'''
return var_contains('CFLAGS', value)
def set_cxxflags(value):
'''
Set the CXXFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cxxflags '-march=native -O2 -pipe'
'''
return set_var('CXXFLAGS', value)
def get_cxxflags():
'''
Get the value of CXXFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cxxflags
'''
return get_var('CXXFLAGS')
def append_cxxflags(value):
'''
Add to or create a new CXXFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cxxflags '-pipe'
'''
return append_var('CXXFLAGS', value)
def trim_cxxflags(value):
'''
Remove a value from CXXFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cxxflags '-pipe'
'''
return trim_var('CXXFLAGS', value)
def cxxflags_contains(value):
'''
Verify if CXXFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cxxflags_contains '-pipe'
'''
return var_contains('CXXFLAGS', value)
def set_chost(value):
'''
Set the CHOST variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_chost 'x86_64-pc-linux-gnu'
'''
return set_var('CHOST', value)
def get_chost():
'''
Get the value of CHOST variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_chost
'''
return get_var('CHOST')
def chost_contains(value):
'''
Verify if CHOST variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.chost_contains 'x86_64-pc-linux-gnu'
'''
return var_contains('CHOST', value)
def set_makeopts(value):
'''
Set the MAKEOPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_makeopts '-j3'
'''
return set_var('MAKEOPTS', value)
def get_makeopts():
'''
Get the value of MAKEOPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_makeopts
'''
return get_var('MAKEOPTS')
def append_makeopts(value):
'''
Add to or create a new MAKEOPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_makeopts '-j3'
'''
return append_var('MAKEOPTS', value)
def trim_makeopts(value):
'''
Remove a value from MAKEOPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_makeopts '-j3'
'''
return trim_var('MAKEOPTS', value)
def makeopts_contains(value):
'''
Verify if MAKEOPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.makeopts_contains '-j3'
'''
return var_contains('MAKEOPTS', value)
def set_emerge_default_opts(value):
'''
Set the EMERGE_DEFAULT_OPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_emerge_default_opts '--jobs'
'''
return set_var('EMERGE_DEFAULT_OPTS', value)
def get_emerge_default_opts():
'''
Get the value of EMERGE_DEFAULT_OPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_emerge_default_opts
'''
return get_var('EMERGE_DEFAULT_OPTS')
def append_emerge_default_opts(value):
'''
Add to or create a new EMERGE_DEFAULT_OPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_emerge_default_opts '--jobs'
'''
return append_var('EMERGE_DEFAULT_OPTS', value)
def trim_emerge_default_opts(value):
'''
Remove a value from EMERGE_DEFAULT_OPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_emerge_default_opts '--jobs'
'''
return trim_var('EMERGE_DEFAULT_OPTS', value)
def emerge_default_opts_contains(value):
'''
Verify if EMERGE_DEFAULT_OPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.emerge_default_opts_contains '--jobs'
'''
return var_contains('EMERGE_DEFAULT_OPTS', value)
def set_gentoo_mirrors(value):
'''
Set the GENTOO_MIRRORS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return set_var('GENTOO_MIRRORS', value)
def get_gentoo_mirrors():
'''
Get the value of GENTOO_MIRRORS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_gentoo_mirrors
'''
return get_var('GENTOO_MIRRORS')
def append_gentoo_mirrors(value):
'''
Add to or create a new GENTOO_MIRRORS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return append_var('GENTOO_MIRRORS', value)
def trim_gentoo_mirrors(value):
'''
Remove a value from GENTOO_MIRRORS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return trim_var('GENTOO_MIRRORS', value)
def gentoo_mirrors_contains(value):
'''
Verify if GENTOO_MIRRORS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.gentoo_mirrors_contains 'http://distfiles.gentoo.org'
'''
return var_contains('GENTOO_MIRRORS', value)
def set_sync(value):
'''
Set the SYNC variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_sync 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return set_var('SYNC', value)
def get_sync():
'''
Get the value of SYNC variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_sync
'''
return get_var('SYNC')
def sync_contains(value):
'''
Verify if SYNC variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.sync_contains 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return var_contains('SYNC', value)
def get_features():
'''
Get the value of FEATURES variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_features
'''
return get_var('FEATURES')
def append_features(value):
'''
Add to or create a new FEATURES in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_features 'webrsync-gpg'
'''
return append_var('FEATURES', value)
def trim_features(value):
'''
Remove a value from FEATURES variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_features 'webrsync-gpg'
'''
return trim_var('FEATURES', value)
def features_contains(value):
'''
Verify if FEATURES variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.features_contains 'webrsync-gpg'
'''
return var_contains('FEATURES', value)
|
saltstack/salt
|
salt/modules/makeconf.py
|
append_var
|
python
|
def append_var(var, value):
'''
Add to or create a new variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, add to its value
if old_value is not None:
appended_value = '{0} {1}'.format(old_value, value)
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var),
'{0}="{1}"'.format(var, appended_value))
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
|
Add to or create a new variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_var 'LINGUAS' 'en'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/makeconf.py#L115-L143
|
[
"def _get_makeconf():\n '''\n Find the correct make.conf. Gentoo recently moved the make.conf\n but still supports the old location, using the old location first\n '''\n old_conf = '/etc/make.conf'\n new_conf = '/etc/portage/make.conf'\n if __salt__['file.file_exists'](old_conf):\n return old_conf\n elif __salt__['file.file_exists'](new_conf):\n return new_conf\n",
"def _add_var(var, value):\n '''\n Add a new var to the make.conf. If using layman, the source line\n for the layman make.conf needs to be at the very end of the\n config. This ensures that the new var will be above the source\n line.\n '''\n makeconf = _get_makeconf()\n layman = 'source /var/lib/layman/make.conf'\n fullvar = '{0}=\"{1}\"'.format(var, value)\n if __salt__['file.contains'](makeconf, layman):\n # TODO perhaps make this a function in the file module?\n cmd = ['sed', '-i', r'/{0}/ i\\{1}'.format(\n layman.replace('/', '\\\\/'),\n fullvar),\n makeconf]\n __salt__['cmd.run'](cmd)\n else:\n __salt__['file.append'](makeconf, fullvar)\n",
"def get_var(var):\n '''\n Get the value of a variable in make.conf\n\n Return the value of the variable or None if the variable is not in\n make.conf\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' makeconf.get_var 'LINGUAS'\n '''\n makeconf = _get_makeconf()\n # Open makeconf\n with salt.utils.files.fopen(makeconf) as fn_:\n conf_file = salt.utils.data.decode(fn_.readlines())\n for line in conf_file:\n if line.startswith(var):\n ret = line.split('=', 1)[1]\n if '\"' in ret:\n ret = ret.split('\"')[1]\n elif '#' in ret:\n ret = ret.split('#')[0]\n ret = ret.strip()\n return ret\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Support for modifying make.conf under Gentoo
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.data
import salt.utils.files
def __virtual__():
'''
Only work on Gentoo
'''
if __grains__['os_family'] == 'Gentoo':
return 'makeconf'
return (False, 'The makeconf execution module cannot be loaded: only available on Gentoo systems.')
def _get_makeconf():
'''
Find the correct make.conf. Gentoo recently moved the make.conf
but still supports the old location, using the old location first
'''
old_conf = '/etc/make.conf'
new_conf = '/etc/portage/make.conf'
if __salt__['file.file_exists'](old_conf):
return old_conf
elif __salt__['file.file_exists'](new_conf):
return new_conf
def _add_var(var, value):
'''
Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line.
'''
makeconf = _get_makeconf()
layman = 'source /var/lib/layman/make.conf'
fullvar = '{0}="{1}"'.format(var, value)
if __salt__['file.contains'](makeconf, layman):
# TODO perhaps make this a function in the file module?
cmd = ['sed', '-i', r'/{0}/ i\{1}'.format(
layman.replace('/', '\\/'),
fullvar),
makeconf]
__salt__['cmd.run'](cmd)
else:
__salt__['file.append'](makeconf, fullvar)
def set_var(var, value):
'''
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, replace its value
if old_value is not None:
__salt__['file.sed'](
makeconf, '^{0}=.*'.format(var), '{0}="{1}"'.format(var, value)
)
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def remove_var(var):
'''
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var is in file
if old_value is not None:
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var), '')
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def trim_var(var, value):
'''
Remove a value from a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var in file, trim value from its value
if old_value is not None:
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def get_var(var):
'''
Get the value of a variable in make.conf
Return the value of the variable or None if the variable is not in
make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_var 'LINGUAS'
'''
makeconf = _get_makeconf()
# Open makeconf
with salt.utils.files.fopen(makeconf) as fn_:
conf_file = salt.utils.data.decode(fn_.readlines())
for line in conf_file:
if line.startswith(var):
ret = line.split('=', 1)[1]
if '"' in ret:
ret = ret.split('"')[1]
elif '#' in ret:
ret = ret.split('#')[0]
ret = ret.strip()
return ret
return None
def var_contains(var, value):
'''
Verify if variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.var_contains 'LINGUAS' 'en'
'''
setval = get_var(var)
# Remove any escaping that was needed to past through salt
value = value.replace('\\', '')
if setval is None:
return False
return value in setval.split()
def set_cflags(value):
'''
Set the CFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cflags '-march=native -O2 -pipe'
'''
return set_var('CFLAGS', value)
def get_cflags():
'''
Get the value of CFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cflags
'''
return get_var('CFLAGS')
def append_cflags(value):
'''
Add to or create a new CFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cflags '-pipe'
'''
return append_var('CFLAGS', value)
def trim_cflags(value):
'''
Remove a value from CFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cflags '-pipe'
'''
return trim_var('CFLAGS', value)
def cflags_contains(value):
'''
Verify if CFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cflags_contains '-pipe'
'''
return var_contains('CFLAGS', value)
def set_cxxflags(value):
'''
Set the CXXFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cxxflags '-march=native -O2 -pipe'
'''
return set_var('CXXFLAGS', value)
def get_cxxflags():
'''
Get the value of CXXFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cxxflags
'''
return get_var('CXXFLAGS')
def append_cxxflags(value):
'''
Add to or create a new CXXFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cxxflags '-pipe'
'''
return append_var('CXXFLAGS', value)
def trim_cxxflags(value):
'''
Remove a value from CXXFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cxxflags '-pipe'
'''
return trim_var('CXXFLAGS', value)
def cxxflags_contains(value):
'''
Verify if CXXFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cxxflags_contains '-pipe'
'''
return var_contains('CXXFLAGS', value)
def set_chost(value):
'''
Set the CHOST variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_chost 'x86_64-pc-linux-gnu'
'''
return set_var('CHOST', value)
def get_chost():
'''
Get the value of CHOST variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_chost
'''
return get_var('CHOST')
def chost_contains(value):
'''
Verify if CHOST variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.chost_contains 'x86_64-pc-linux-gnu'
'''
return var_contains('CHOST', value)
def set_makeopts(value):
'''
Set the MAKEOPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_makeopts '-j3'
'''
return set_var('MAKEOPTS', value)
def get_makeopts():
'''
Get the value of MAKEOPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_makeopts
'''
return get_var('MAKEOPTS')
def append_makeopts(value):
'''
Add to or create a new MAKEOPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_makeopts '-j3'
'''
return append_var('MAKEOPTS', value)
def trim_makeopts(value):
'''
Remove a value from MAKEOPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_makeopts '-j3'
'''
return trim_var('MAKEOPTS', value)
def makeopts_contains(value):
'''
Verify if MAKEOPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.makeopts_contains '-j3'
'''
return var_contains('MAKEOPTS', value)
def set_emerge_default_opts(value):
'''
Set the EMERGE_DEFAULT_OPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_emerge_default_opts '--jobs'
'''
return set_var('EMERGE_DEFAULT_OPTS', value)
def get_emerge_default_opts():
'''
Get the value of EMERGE_DEFAULT_OPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_emerge_default_opts
'''
return get_var('EMERGE_DEFAULT_OPTS')
def append_emerge_default_opts(value):
'''
Add to or create a new EMERGE_DEFAULT_OPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_emerge_default_opts '--jobs'
'''
return append_var('EMERGE_DEFAULT_OPTS', value)
def trim_emerge_default_opts(value):
'''
Remove a value from EMERGE_DEFAULT_OPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_emerge_default_opts '--jobs'
'''
return trim_var('EMERGE_DEFAULT_OPTS', value)
def emerge_default_opts_contains(value):
'''
Verify if EMERGE_DEFAULT_OPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.emerge_default_opts_contains '--jobs'
'''
return var_contains('EMERGE_DEFAULT_OPTS', value)
def set_gentoo_mirrors(value):
'''
Set the GENTOO_MIRRORS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return set_var('GENTOO_MIRRORS', value)
def get_gentoo_mirrors():
'''
Get the value of GENTOO_MIRRORS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_gentoo_mirrors
'''
return get_var('GENTOO_MIRRORS')
def append_gentoo_mirrors(value):
'''
Add to or create a new GENTOO_MIRRORS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return append_var('GENTOO_MIRRORS', value)
def trim_gentoo_mirrors(value):
'''
Remove a value from GENTOO_MIRRORS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return trim_var('GENTOO_MIRRORS', value)
def gentoo_mirrors_contains(value):
'''
Verify if GENTOO_MIRRORS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.gentoo_mirrors_contains 'http://distfiles.gentoo.org'
'''
return var_contains('GENTOO_MIRRORS', value)
def set_sync(value):
'''
Set the SYNC variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_sync 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return set_var('SYNC', value)
def get_sync():
'''
Get the value of SYNC variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_sync
'''
return get_var('SYNC')
def sync_contains(value):
'''
Verify if SYNC variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.sync_contains 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return var_contains('SYNC', value)
def get_features():
'''
Get the value of FEATURES variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_features
'''
return get_var('FEATURES')
def append_features(value):
'''
Add to or create a new FEATURES in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_features 'webrsync-gpg'
'''
return append_var('FEATURES', value)
def trim_features(value):
'''
Remove a value from FEATURES variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_features 'webrsync-gpg'
'''
return trim_var('FEATURES', value)
def features_contains(value):
'''
Verify if FEATURES variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.features_contains 'webrsync-gpg'
'''
return var_contains('FEATURES', value)
|
saltstack/salt
|
salt/modules/makeconf.py
|
trim_var
|
python
|
def trim_var(var, value):
'''
Remove a value from a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var in file, trim value from its value
if old_value is not None:
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
|
Remove a value from a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_var 'LINGUAS' 'en'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/makeconf.py#L146-L170
|
[
"def _get_makeconf():\n '''\n Find the correct make.conf. Gentoo recently moved the make.conf\n but still supports the old location, using the old location first\n '''\n old_conf = '/etc/make.conf'\n new_conf = '/etc/portage/make.conf'\n if __salt__['file.file_exists'](old_conf):\n return old_conf\n elif __salt__['file.file_exists'](new_conf):\n return new_conf\n",
"def get_var(var):\n '''\n Get the value of a variable in make.conf\n\n Return the value of the variable or None if the variable is not in\n make.conf\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' makeconf.get_var 'LINGUAS'\n '''\n makeconf = _get_makeconf()\n # Open makeconf\n with salt.utils.files.fopen(makeconf) as fn_:\n conf_file = salt.utils.data.decode(fn_.readlines())\n for line in conf_file:\n if line.startswith(var):\n ret = line.split('=', 1)[1]\n if '\"' in ret:\n ret = ret.split('\"')[1]\n elif '#' in ret:\n ret = ret.split('#')[0]\n ret = ret.strip()\n return ret\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Support for modifying make.conf under Gentoo
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.data
import salt.utils.files
def __virtual__():
'''
Only work on Gentoo
'''
if __grains__['os_family'] == 'Gentoo':
return 'makeconf'
return (False, 'The makeconf execution module cannot be loaded: only available on Gentoo systems.')
def _get_makeconf():
'''
Find the correct make.conf. Gentoo recently moved the make.conf
but still supports the old location, using the old location first
'''
old_conf = '/etc/make.conf'
new_conf = '/etc/portage/make.conf'
if __salt__['file.file_exists'](old_conf):
return old_conf
elif __salt__['file.file_exists'](new_conf):
return new_conf
def _add_var(var, value):
'''
Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line.
'''
makeconf = _get_makeconf()
layman = 'source /var/lib/layman/make.conf'
fullvar = '{0}="{1}"'.format(var, value)
if __salt__['file.contains'](makeconf, layman):
# TODO perhaps make this a function in the file module?
cmd = ['sed', '-i', r'/{0}/ i\{1}'.format(
layman.replace('/', '\\/'),
fullvar),
makeconf]
__salt__['cmd.run'](cmd)
else:
__salt__['file.append'](makeconf, fullvar)
def set_var(var, value):
'''
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, replace its value
if old_value is not None:
__salt__['file.sed'](
makeconf, '^{0}=.*'.format(var), '{0}="{1}"'.format(var, value)
)
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def remove_var(var):
'''
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var is in file
if old_value is not None:
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var), '')
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def append_var(var, value):
'''
Add to or create a new variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, add to its value
if old_value is not None:
appended_value = '{0} {1}'.format(old_value, value)
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var),
'{0}="{1}"'.format(var, appended_value))
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def get_var(var):
'''
Get the value of a variable in make.conf
Return the value of the variable or None if the variable is not in
make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_var 'LINGUAS'
'''
makeconf = _get_makeconf()
# Open makeconf
with salt.utils.files.fopen(makeconf) as fn_:
conf_file = salt.utils.data.decode(fn_.readlines())
for line in conf_file:
if line.startswith(var):
ret = line.split('=', 1)[1]
if '"' in ret:
ret = ret.split('"')[1]
elif '#' in ret:
ret = ret.split('#')[0]
ret = ret.strip()
return ret
return None
def var_contains(var, value):
'''
Verify if variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.var_contains 'LINGUAS' 'en'
'''
setval = get_var(var)
# Remove any escaping that was needed to past through salt
value = value.replace('\\', '')
if setval is None:
return False
return value in setval.split()
def set_cflags(value):
'''
Set the CFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cflags '-march=native -O2 -pipe'
'''
return set_var('CFLAGS', value)
def get_cflags():
'''
Get the value of CFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cflags
'''
return get_var('CFLAGS')
def append_cflags(value):
'''
Add to or create a new CFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cflags '-pipe'
'''
return append_var('CFLAGS', value)
def trim_cflags(value):
'''
Remove a value from CFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cflags '-pipe'
'''
return trim_var('CFLAGS', value)
def cflags_contains(value):
'''
Verify if CFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cflags_contains '-pipe'
'''
return var_contains('CFLAGS', value)
def set_cxxflags(value):
'''
Set the CXXFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cxxflags '-march=native -O2 -pipe'
'''
return set_var('CXXFLAGS', value)
def get_cxxflags():
'''
Get the value of CXXFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cxxflags
'''
return get_var('CXXFLAGS')
def append_cxxflags(value):
'''
Add to or create a new CXXFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cxxflags '-pipe'
'''
return append_var('CXXFLAGS', value)
def trim_cxxflags(value):
'''
Remove a value from CXXFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cxxflags '-pipe'
'''
return trim_var('CXXFLAGS', value)
def cxxflags_contains(value):
'''
Verify if CXXFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cxxflags_contains '-pipe'
'''
return var_contains('CXXFLAGS', value)
def set_chost(value):
'''
Set the CHOST variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_chost 'x86_64-pc-linux-gnu'
'''
return set_var('CHOST', value)
def get_chost():
'''
Get the value of CHOST variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_chost
'''
return get_var('CHOST')
def chost_contains(value):
'''
Verify if CHOST variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.chost_contains 'x86_64-pc-linux-gnu'
'''
return var_contains('CHOST', value)
def set_makeopts(value):
'''
Set the MAKEOPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_makeopts '-j3'
'''
return set_var('MAKEOPTS', value)
def get_makeopts():
'''
Get the value of MAKEOPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_makeopts
'''
return get_var('MAKEOPTS')
def append_makeopts(value):
'''
Add to or create a new MAKEOPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_makeopts '-j3'
'''
return append_var('MAKEOPTS', value)
def trim_makeopts(value):
'''
Remove a value from MAKEOPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_makeopts '-j3'
'''
return trim_var('MAKEOPTS', value)
def makeopts_contains(value):
'''
Verify if MAKEOPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.makeopts_contains '-j3'
'''
return var_contains('MAKEOPTS', value)
def set_emerge_default_opts(value):
'''
Set the EMERGE_DEFAULT_OPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_emerge_default_opts '--jobs'
'''
return set_var('EMERGE_DEFAULT_OPTS', value)
def get_emerge_default_opts():
'''
Get the value of EMERGE_DEFAULT_OPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_emerge_default_opts
'''
return get_var('EMERGE_DEFAULT_OPTS')
def append_emerge_default_opts(value):
'''
Add to or create a new EMERGE_DEFAULT_OPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_emerge_default_opts '--jobs'
'''
return append_var('EMERGE_DEFAULT_OPTS', value)
def trim_emerge_default_opts(value):
'''
Remove a value from EMERGE_DEFAULT_OPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_emerge_default_opts '--jobs'
'''
return trim_var('EMERGE_DEFAULT_OPTS', value)
def emerge_default_opts_contains(value):
'''
Verify if EMERGE_DEFAULT_OPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.emerge_default_opts_contains '--jobs'
'''
return var_contains('EMERGE_DEFAULT_OPTS', value)
def set_gentoo_mirrors(value):
'''
Set the GENTOO_MIRRORS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return set_var('GENTOO_MIRRORS', value)
def get_gentoo_mirrors():
'''
Get the value of GENTOO_MIRRORS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_gentoo_mirrors
'''
return get_var('GENTOO_MIRRORS')
def append_gentoo_mirrors(value):
'''
Add to or create a new GENTOO_MIRRORS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return append_var('GENTOO_MIRRORS', value)
def trim_gentoo_mirrors(value):
'''
Remove a value from GENTOO_MIRRORS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return trim_var('GENTOO_MIRRORS', value)
def gentoo_mirrors_contains(value):
'''
Verify if GENTOO_MIRRORS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.gentoo_mirrors_contains 'http://distfiles.gentoo.org'
'''
return var_contains('GENTOO_MIRRORS', value)
def set_sync(value):
'''
Set the SYNC variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_sync 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return set_var('SYNC', value)
def get_sync():
'''
Get the value of SYNC variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_sync
'''
return get_var('SYNC')
def sync_contains(value):
'''
Verify if SYNC variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.sync_contains 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return var_contains('SYNC', value)
def get_features():
'''
Get the value of FEATURES variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_features
'''
return get_var('FEATURES')
def append_features(value):
'''
Add to or create a new FEATURES in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_features 'webrsync-gpg'
'''
return append_var('FEATURES', value)
def trim_features(value):
'''
Remove a value from FEATURES variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_features 'webrsync-gpg'
'''
return trim_var('FEATURES', value)
def features_contains(value):
'''
Verify if FEATURES variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.features_contains 'webrsync-gpg'
'''
return var_contains('FEATURES', value)
|
saltstack/salt
|
salt/modules/makeconf.py
|
get_var
|
python
|
def get_var(var):
'''
Get the value of a variable in make.conf
Return the value of the variable or None if the variable is not in
make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_var 'LINGUAS'
'''
makeconf = _get_makeconf()
# Open makeconf
with salt.utils.files.fopen(makeconf) as fn_:
conf_file = salt.utils.data.decode(fn_.readlines())
for line in conf_file:
if line.startswith(var):
ret = line.split('=', 1)[1]
if '"' in ret:
ret = ret.split('"')[1]
elif '#' in ret:
ret = ret.split('#')[0]
ret = ret.strip()
return ret
return None
|
Get the value of a variable in make.conf
Return the value of the variable or None if the variable is not in
make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_var 'LINGUAS'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/makeconf.py#L173-L199
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _get_makeconf():\n '''\n Find the correct make.conf. Gentoo recently moved the make.conf\n but still supports the old location, using the old location first\n '''\n old_conf = '/etc/make.conf'\n new_conf = '/etc/portage/make.conf'\n if __salt__['file.file_exists'](old_conf):\n return old_conf\n elif __salt__['file.file_exists'](new_conf):\n return new_conf\n"
] |
# -*- coding: utf-8 -*-
'''
Support for modifying make.conf under Gentoo
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.data
import salt.utils.files
def __virtual__():
'''
Only work on Gentoo
'''
if __grains__['os_family'] == 'Gentoo':
return 'makeconf'
return (False, 'The makeconf execution module cannot be loaded: only available on Gentoo systems.')
def _get_makeconf():
'''
Find the correct make.conf. Gentoo recently moved the make.conf
but still supports the old location, using the old location first
'''
old_conf = '/etc/make.conf'
new_conf = '/etc/portage/make.conf'
if __salt__['file.file_exists'](old_conf):
return old_conf
elif __salt__['file.file_exists'](new_conf):
return new_conf
def _add_var(var, value):
'''
Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line.
'''
makeconf = _get_makeconf()
layman = 'source /var/lib/layman/make.conf'
fullvar = '{0}="{1}"'.format(var, value)
if __salt__['file.contains'](makeconf, layman):
# TODO perhaps make this a function in the file module?
cmd = ['sed', '-i', r'/{0}/ i\{1}'.format(
layman.replace('/', '\\/'),
fullvar),
makeconf]
__salt__['cmd.run'](cmd)
else:
__salt__['file.append'](makeconf, fullvar)
def set_var(var, value):
'''
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, replace its value
if old_value is not None:
__salt__['file.sed'](
makeconf, '^{0}=.*'.format(var), '{0}="{1}"'.format(var, value)
)
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def remove_var(var):
'''
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var is in file
if old_value is not None:
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var), '')
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def append_var(var, value):
'''
Add to or create a new variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, add to its value
if old_value is not None:
appended_value = '{0} {1}'.format(old_value, value)
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var),
'{0}="{1}"'.format(var, appended_value))
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def trim_var(var, value):
'''
Remove a value from a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var in file, trim value from its value
if old_value is not None:
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def var_contains(var, value):
'''
Verify if variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.var_contains 'LINGUAS' 'en'
'''
setval = get_var(var)
# Remove any escaping that was needed to past through salt
value = value.replace('\\', '')
if setval is None:
return False
return value in setval.split()
def set_cflags(value):
'''
Set the CFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cflags '-march=native -O2 -pipe'
'''
return set_var('CFLAGS', value)
def get_cflags():
'''
Get the value of CFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cflags
'''
return get_var('CFLAGS')
def append_cflags(value):
'''
Add to or create a new CFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cflags '-pipe'
'''
return append_var('CFLAGS', value)
def trim_cflags(value):
'''
Remove a value from CFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cflags '-pipe'
'''
return trim_var('CFLAGS', value)
def cflags_contains(value):
'''
Verify if CFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cflags_contains '-pipe'
'''
return var_contains('CFLAGS', value)
def set_cxxflags(value):
'''
Set the CXXFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cxxflags '-march=native -O2 -pipe'
'''
return set_var('CXXFLAGS', value)
def get_cxxflags():
'''
Get the value of CXXFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cxxflags
'''
return get_var('CXXFLAGS')
def append_cxxflags(value):
'''
Add to or create a new CXXFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cxxflags '-pipe'
'''
return append_var('CXXFLAGS', value)
def trim_cxxflags(value):
'''
Remove a value from CXXFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cxxflags '-pipe'
'''
return trim_var('CXXFLAGS', value)
def cxxflags_contains(value):
'''
Verify if CXXFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cxxflags_contains '-pipe'
'''
return var_contains('CXXFLAGS', value)
def set_chost(value):
'''
Set the CHOST variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_chost 'x86_64-pc-linux-gnu'
'''
return set_var('CHOST', value)
def get_chost():
'''
Get the value of CHOST variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_chost
'''
return get_var('CHOST')
def chost_contains(value):
'''
Verify if CHOST variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.chost_contains 'x86_64-pc-linux-gnu'
'''
return var_contains('CHOST', value)
def set_makeopts(value):
'''
Set the MAKEOPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_makeopts '-j3'
'''
return set_var('MAKEOPTS', value)
def get_makeopts():
'''
Get the value of MAKEOPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_makeopts
'''
return get_var('MAKEOPTS')
def append_makeopts(value):
'''
Add to or create a new MAKEOPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_makeopts '-j3'
'''
return append_var('MAKEOPTS', value)
def trim_makeopts(value):
'''
Remove a value from MAKEOPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_makeopts '-j3'
'''
return trim_var('MAKEOPTS', value)
def makeopts_contains(value):
'''
Verify if MAKEOPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.makeopts_contains '-j3'
'''
return var_contains('MAKEOPTS', value)
def set_emerge_default_opts(value):
'''
Set the EMERGE_DEFAULT_OPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_emerge_default_opts '--jobs'
'''
return set_var('EMERGE_DEFAULT_OPTS', value)
def get_emerge_default_opts():
'''
Get the value of EMERGE_DEFAULT_OPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_emerge_default_opts
'''
return get_var('EMERGE_DEFAULT_OPTS')
def append_emerge_default_opts(value):
'''
Add to or create a new EMERGE_DEFAULT_OPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_emerge_default_opts '--jobs'
'''
return append_var('EMERGE_DEFAULT_OPTS', value)
def trim_emerge_default_opts(value):
'''
Remove a value from EMERGE_DEFAULT_OPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_emerge_default_opts '--jobs'
'''
return trim_var('EMERGE_DEFAULT_OPTS', value)
def emerge_default_opts_contains(value):
'''
Verify if EMERGE_DEFAULT_OPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.emerge_default_opts_contains '--jobs'
'''
return var_contains('EMERGE_DEFAULT_OPTS', value)
def set_gentoo_mirrors(value):
'''
Set the GENTOO_MIRRORS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return set_var('GENTOO_MIRRORS', value)
def get_gentoo_mirrors():
'''
Get the value of GENTOO_MIRRORS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_gentoo_mirrors
'''
return get_var('GENTOO_MIRRORS')
def append_gentoo_mirrors(value):
'''
Add to or create a new GENTOO_MIRRORS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return append_var('GENTOO_MIRRORS', value)
def trim_gentoo_mirrors(value):
'''
Remove a value from GENTOO_MIRRORS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return trim_var('GENTOO_MIRRORS', value)
def gentoo_mirrors_contains(value):
'''
Verify if GENTOO_MIRRORS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.gentoo_mirrors_contains 'http://distfiles.gentoo.org'
'''
return var_contains('GENTOO_MIRRORS', value)
def set_sync(value):
'''
Set the SYNC variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_sync 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return set_var('SYNC', value)
def get_sync():
'''
Get the value of SYNC variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_sync
'''
return get_var('SYNC')
def sync_contains(value):
'''
Verify if SYNC variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.sync_contains 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return var_contains('SYNC', value)
def get_features():
'''
Get the value of FEATURES variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_features
'''
return get_var('FEATURES')
def append_features(value):
'''
Add to or create a new FEATURES in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_features 'webrsync-gpg'
'''
return append_var('FEATURES', value)
def trim_features(value):
'''
Remove a value from FEATURES variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_features 'webrsync-gpg'
'''
return trim_var('FEATURES', value)
def features_contains(value):
'''
Verify if FEATURES variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.features_contains 'webrsync-gpg'
'''
return var_contains('FEATURES', value)
|
saltstack/salt
|
salt/modules/makeconf.py
|
var_contains
|
python
|
def var_contains(var, value):
'''
Verify if variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.var_contains 'LINGUAS' 'en'
'''
setval = get_var(var)
# Remove any escaping that was needed to past through salt
value = value.replace('\\', '')
if setval is None:
return False
return value in setval.split()
|
Verify if variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.var_contains 'LINGUAS' 'en'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/makeconf.py#L202-L219
|
[
"def get_var(var):\n '''\n Get the value of a variable in make.conf\n\n Return the value of the variable or None if the variable is not in\n make.conf\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' makeconf.get_var 'LINGUAS'\n '''\n makeconf = _get_makeconf()\n # Open makeconf\n with salt.utils.files.fopen(makeconf) as fn_:\n conf_file = salt.utils.data.decode(fn_.readlines())\n for line in conf_file:\n if line.startswith(var):\n ret = line.split('=', 1)[1]\n if '\"' in ret:\n ret = ret.split('\"')[1]\n elif '#' in ret:\n ret = ret.split('#')[0]\n ret = ret.strip()\n return ret\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Support for modifying make.conf under Gentoo
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.data
import salt.utils.files
def __virtual__():
'''
Only work on Gentoo
'''
if __grains__['os_family'] == 'Gentoo':
return 'makeconf'
return (False, 'The makeconf execution module cannot be loaded: only available on Gentoo systems.')
def _get_makeconf():
'''
Find the correct make.conf. Gentoo recently moved the make.conf
but still supports the old location, using the old location first
'''
old_conf = '/etc/make.conf'
new_conf = '/etc/portage/make.conf'
if __salt__['file.file_exists'](old_conf):
return old_conf
elif __salt__['file.file_exists'](new_conf):
return new_conf
def _add_var(var, value):
'''
Add a new var to the make.conf. If using layman, the source line
for the layman make.conf needs to be at the very end of the
config. This ensures that the new var will be above the source
line.
'''
makeconf = _get_makeconf()
layman = 'source /var/lib/layman/make.conf'
fullvar = '{0}="{1}"'.format(var, value)
if __salt__['file.contains'](makeconf, layman):
# TODO perhaps make this a function in the file module?
cmd = ['sed', '-i', r'/{0}/ i\{1}'.format(
layman.replace('/', '\\/'),
fullvar),
makeconf]
__salt__['cmd.run'](cmd)
else:
__salt__['file.append'](makeconf, fullvar)
def set_var(var, value):
'''
Set a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, replace its value
if old_value is not None:
__salt__['file.sed'](
makeconf, '^{0}=.*'.format(var), '{0}="{1}"'.format(var, value)
)
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def remove_var(var):
'''
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var is in file
if old_value is not None:
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var), '')
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def append_var(var, value):
'''
Add to or create a new variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var already in file, add to its value
if old_value is not None:
appended_value = '{0} {1}'.format(old_value, value)
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var),
'{0}="{1}"'.format(var, appended_value))
else:
_add_var(var, value)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def trim_var(var, value):
'''
Remove a value from a variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_var 'LINGUAS' 'en'
'''
makeconf = _get_makeconf()
old_value = get_var(var)
# If var in file, trim value from its value
if old_value is not None:
__salt__['file.sed'](makeconf, value, '', limit=var)
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
def get_var(var):
'''
Get the value of a variable in make.conf
Return the value of the variable or None if the variable is not in
make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_var 'LINGUAS'
'''
makeconf = _get_makeconf()
# Open makeconf
with salt.utils.files.fopen(makeconf) as fn_:
conf_file = salt.utils.data.decode(fn_.readlines())
for line in conf_file:
if line.startswith(var):
ret = line.split('=', 1)[1]
if '"' in ret:
ret = ret.split('"')[1]
elif '#' in ret:
ret = ret.split('#')[0]
ret = ret.strip()
return ret
return None
def set_cflags(value):
'''
Set the CFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cflags '-march=native -O2 -pipe'
'''
return set_var('CFLAGS', value)
def get_cflags():
'''
Get the value of CFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cflags
'''
return get_var('CFLAGS')
def append_cflags(value):
'''
Add to or create a new CFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cflags '-pipe'
'''
return append_var('CFLAGS', value)
def trim_cflags(value):
'''
Remove a value from CFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cflags '-pipe'
'''
return trim_var('CFLAGS', value)
def cflags_contains(value):
'''
Verify if CFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cflags_contains '-pipe'
'''
return var_contains('CFLAGS', value)
def set_cxxflags(value):
'''
Set the CXXFLAGS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_cxxflags '-march=native -O2 -pipe'
'''
return set_var('CXXFLAGS', value)
def get_cxxflags():
'''
Get the value of CXXFLAGS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_cxxflags
'''
return get_var('CXXFLAGS')
def append_cxxflags(value):
'''
Add to or create a new CXXFLAGS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_cxxflags '-pipe'
'''
return append_var('CXXFLAGS', value)
def trim_cxxflags(value):
'''
Remove a value from CXXFLAGS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_cxxflags '-pipe'
'''
return trim_var('CXXFLAGS', value)
def cxxflags_contains(value):
'''
Verify if CXXFLAGS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.cxxflags_contains '-pipe'
'''
return var_contains('CXXFLAGS', value)
def set_chost(value):
'''
Set the CHOST variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_chost 'x86_64-pc-linux-gnu'
'''
return set_var('CHOST', value)
def get_chost():
'''
Get the value of CHOST variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_chost
'''
return get_var('CHOST')
def chost_contains(value):
'''
Verify if CHOST variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.chost_contains 'x86_64-pc-linux-gnu'
'''
return var_contains('CHOST', value)
def set_makeopts(value):
'''
Set the MAKEOPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_makeopts '-j3'
'''
return set_var('MAKEOPTS', value)
def get_makeopts():
'''
Get the value of MAKEOPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_makeopts
'''
return get_var('MAKEOPTS')
def append_makeopts(value):
'''
Add to or create a new MAKEOPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_makeopts '-j3'
'''
return append_var('MAKEOPTS', value)
def trim_makeopts(value):
'''
Remove a value from MAKEOPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_makeopts '-j3'
'''
return trim_var('MAKEOPTS', value)
def makeopts_contains(value):
'''
Verify if MAKEOPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.makeopts_contains '-j3'
'''
return var_contains('MAKEOPTS', value)
def set_emerge_default_opts(value):
'''
Set the EMERGE_DEFAULT_OPTS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_emerge_default_opts '--jobs'
'''
return set_var('EMERGE_DEFAULT_OPTS', value)
def get_emerge_default_opts():
'''
Get the value of EMERGE_DEFAULT_OPTS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_emerge_default_opts
'''
return get_var('EMERGE_DEFAULT_OPTS')
def append_emerge_default_opts(value):
'''
Add to or create a new EMERGE_DEFAULT_OPTS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_emerge_default_opts '--jobs'
'''
return append_var('EMERGE_DEFAULT_OPTS', value)
def trim_emerge_default_opts(value):
'''
Remove a value from EMERGE_DEFAULT_OPTS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_emerge_default_opts '--jobs'
'''
return trim_var('EMERGE_DEFAULT_OPTS', value)
def emerge_default_opts_contains(value):
'''
Verify if EMERGE_DEFAULT_OPTS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.emerge_default_opts_contains '--jobs'
'''
return var_contains('EMERGE_DEFAULT_OPTS', value)
def set_gentoo_mirrors(value):
'''
Set the GENTOO_MIRRORS variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return set_var('GENTOO_MIRRORS', value)
def get_gentoo_mirrors():
'''
Get the value of GENTOO_MIRRORS variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_gentoo_mirrors
'''
return get_var('GENTOO_MIRRORS')
def append_gentoo_mirrors(value):
'''
Add to or create a new GENTOO_MIRRORS in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return append_var('GENTOO_MIRRORS', value)
def trim_gentoo_mirrors(value):
'''
Remove a value from GENTOO_MIRRORS variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_gentoo_mirrors 'http://distfiles.gentoo.org'
'''
return trim_var('GENTOO_MIRRORS', value)
def gentoo_mirrors_contains(value):
'''
Verify if GENTOO_MIRRORS variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.gentoo_mirrors_contains 'http://distfiles.gentoo.org'
'''
return var_contains('GENTOO_MIRRORS', value)
def set_sync(value):
'''
Set the SYNC variable
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.set_sync 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return set_var('SYNC', value)
def get_sync():
'''
Get the value of SYNC variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_sync
'''
return get_var('SYNC')
def sync_contains(value):
'''
Verify if SYNC variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.sync_contains 'rsync://rsync.namerica.gentoo.org/gentoo-portage'
'''
return var_contains('SYNC', value)
def get_features():
'''
Get the value of FEATURES variable in the make.conf
Return the value of the variable or None if the variable is
not in the make.conf
CLI Example:
.. code-block:: bash
salt '*' makeconf.get_features
'''
return get_var('FEATURES')
def append_features(value):
'''
Add to or create a new FEATURES in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.append_features 'webrsync-gpg'
'''
return append_var('FEATURES', value)
def trim_features(value):
'''
Remove a value from FEATURES variable in the make.conf
Return a dict containing the new value for variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.trim_features 'webrsync-gpg'
'''
return trim_var('FEATURES', value)
def features_contains(value):
'''
Verify if FEATURES variable contains a value in make.conf
Return True if value is set for var
CLI Example:
.. code-block:: bash
salt '*' makeconf.features_contains 'webrsync-gpg'
'''
return var_contains('FEATURES', value)
|
saltstack/salt
|
salt/returners/carbon_return.py
|
_carbon
|
python
|
def _carbon(host, port):
'''
Context manager to ensure the clean creation and destruction of a socket.
host
The IP or hostname of the carbon server
port
The port that carbon is listening on
'''
carbon_sock = None
try:
carbon_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
carbon_sock.connect((host, port))
except socket.error as err:
log.error('Error connecting to %s:%s, %s', host, port, err)
raise
else:
log.debug('Connected to carbon')
yield carbon_sock
finally:
if carbon_sock is not None:
# Shut down and close socket
log.debug('Destroying carbon socket')
carbon_sock.shutdown(socket.SHUT_RDWR)
carbon_sock.close()
|
Context manager to ensure the clean creation and destruction of a socket.
host
The IP or hostname of the carbon server
port
The port that carbon is listening on
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/carbon_return.py#L129-L157
| null |
# -*- coding: utf-8 -*-
'''
Take data from salt and "return" it into a carbon receiver
Add the following configuration to the minion configuration file:
.. code-block:: yaml
carbon.host: <server ip address>
carbon.port: 2003
Errors when trying to convert data to numbers may be ignored by setting
``carbon.skip_on_error`` to `True`:
.. code-block:: yaml
carbon.skip_on_error: True
By default, data will be sent to carbon using the plaintext protocol. To use
the pickle protocol, set ``carbon.mode`` to ``pickle``:
.. code-block:: yaml
carbon.mode: pickle
You can also specify the pattern used for the metric base path (except for virt modules metrics):
carbon.metric_base_pattern: carbon.[minion_id].[module].[function]
These tokens can used :
[module]: salt module
[function]: salt function
[minion_id]: minion id
Default is :
carbon.metric_base_pattern: [module].[function].[minion_id]
Carbon settings may also be configured as:
.. code-block:: yaml
carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
metric_base_pattern: <pattern> | [module].[function].[minion_id]
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
To use the carbon returner, append '--return carbon' to the salt command.
.. code-block:: bash
salt '*' test.ping --return carbon
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_kwargs '{"skip_on_error": False}'
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import logging
import socket
import struct
import time
from contextlib import contextmanager
# Import salt libs
import salt.utils.jid
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import cPickle, map # pylint: disable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'carbon'
def __virtual__():
return __virtualname__
def _get_options(ret):
'''
Returns options used for the carbon returner.
'''
attrs = {'host': 'host',
'port': 'port',
'skip': 'skip_on_error',
'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@contextmanager
def _send_picklemetrics(metrics):
'''
Format metrics for the carbon pickle protocol
'''
metrics = [(metric_name, (timestamp, value))
for (metric_name, value, timestamp) in metrics]
data = cPickle.dumps(metrics, -1)
payload = struct.pack(b'!L', len(data)) + data
return payload
def _send_textmetrics(metrics):
'''
Format metrics for the carbon plaintext protocol
'''
data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']
return '\n'.join(data)
def _walk(path, value, metrics, timestamp, skip):
'''
Recursively include metrics from *value*.
path
The dot-separated path of the metric.
value
A dictionary or value from a dictionary. If a dictionary, ``_walk``
will be called again with the each key/value pair as a new set of
metrics.
metrics
The list of metrics that will be sent to carbon, formatted as::
(path, value, timestamp)
skip
Whether or not to skip metrics when there's an error casting the value
to a float. Defaults to `False`.
'''
log.trace(
'Carbon return walking path: %s, value: %s, metrics: %s, '
'timestamp: %s', path, value, metrics, timestamp
)
if isinstance(value, collections.Mapping):
for key, val in six.iteritems(value):
_walk('{0}.{1}'.format(path, key), val, metrics, timestamp, skip)
elif isinstance(value, list):
for item in value:
_walk('{0}.{1}'.format(path, item), item, metrics, timestamp, skip)
else:
try:
val = float(value)
metrics.append((path, val, timestamp))
except (TypeError, ValueError):
msg = 'Error in carbon returner, when trying to convert metric: ' \
'{0}, with val: {1}'.format(path, value)
if skip:
log.debug(msg)
else:
log.info(msg)
raise
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carbon minion configured with host: %s:%s', host, port)
log.debug('Using carbon protocol: %s', mode)
if not (host and port):
log.error('Host or port not defined')
return
# TODO: possible to use time return from salt job to be slightly more precise?
# convert the jid to unix timestamp?
# {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}
timestamp = int(time.time())
handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics
metrics = []
log.trace('Carbon returning walking data: %s', saltdata)
_walk(metric_base, saltdata, metrics, timestamp, skip)
data = handler(metrics)
log.trace('Carbon inserting data: %s', data)
with _carbon(host, port) as sock:
total_sent_bytes = 0
while total_sent_bytes < len(data):
sent_bytes = sock.send(data[total_sent_bytes:])
if sent_bytes == 0:
log.error('Bytes sent 0, Connection reset?')
return
log.debug('Sent %s bytes to carbon', sent_bytes)
total_sent_bytes += sent_bytes
def event_return(events):
'''
Return event data to remote carbon server
Provide a list of events to be stored in carbon
'''
opts = _get_options({}) # Pass in empty ret, since this is a list of events
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: %s', event)
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
def returner(ret):
'''
Return data to a remote carbon server using the text metric protocol
Each metric will look like::
[module].[function].[minion_id].[metric path [...]].[metric name]
'''
opts = _get_options(ret)
metric_base = ret['fun']
# Strip the hostname from the carbon base if we are returning from virt
# module since then we will get stable metric bases even if the VM is
# migrate from host to host
if not metric_base.startswith('virt.'):
metric_base += '.' + ret['id'].replace('.', '_')
saltdata = ret['return']
_send(saltdata, metric_base, opts)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/carbon_return.py
|
_send_picklemetrics
|
python
|
def _send_picklemetrics(metrics):
'''
Format metrics for the carbon pickle protocol
'''
metrics = [(metric_name, (timestamp, value))
for (metric_name, value, timestamp) in metrics]
data = cPickle.dumps(metrics, -1)
payload = struct.pack(b'!L', len(data)) + data
return payload
|
Format metrics for the carbon pickle protocol
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/carbon_return.py#L160-L171
| null |
# -*- coding: utf-8 -*-
'''
Take data from salt and "return" it into a carbon receiver
Add the following configuration to the minion configuration file:
.. code-block:: yaml
carbon.host: <server ip address>
carbon.port: 2003
Errors when trying to convert data to numbers may be ignored by setting
``carbon.skip_on_error`` to `True`:
.. code-block:: yaml
carbon.skip_on_error: True
By default, data will be sent to carbon using the plaintext protocol. To use
the pickle protocol, set ``carbon.mode`` to ``pickle``:
.. code-block:: yaml
carbon.mode: pickle
You can also specify the pattern used for the metric base path (except for virt modules metrics):
carbon.metric_base_pattern: carbon.[minion_id].[module].[function]
These tokens can used :
[module]: salt module
[function]: salt function
[minion_id]: minion id
Default is :
carbon.metric_base_pattern: [module].[function].[minion_id]
Carbon settings may also be configured as:
.. code-block:: yaml
carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
metric_base_pattern: <pattern> | [module].[function].[minion_id]
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
To use the carbon returner, append '--return carbon' to the salt command.
.. code-block:: bash
salt '*' test.ping --return carbon
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_kwargs '{"skip_on_error": False}'
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import logging
import socket
import struct
import time
from contextlib import contextmanager
# Import salt libs
import salt.utils.jid
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import cPickle, map # pylint: disable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'carbon'
def __virtual__():
return __virtualname__
def _get_options(ret):
'''
Returns options used for the carbon returner.
'''
attrs = {'host': 'host',
'port': 'port',
'skip': 'skip_on_error',
'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@contextmanager
def _carbon(host, port):
'''
Context manager to ensure the clean creation and destruction of a socket.
host
The IP or hostname of the carbon server
port
The port that carbon is listening on
'''
carbon_sock = None
try:
carbon_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
carbon_sock.connect((host, port))
except socket.error as err:
log.error('Error connecting to %s:%s, %s', host, port, err)
raise
else:
log.debug('Connected to carbon')
yield carbon_sock
finally:
if carbon_sock is not None:
# Shut down and close socket
log.debug('Destroying carbon socket')
carbon_sock.shutdown(socket.SHUT_RDWR)
carbon_sock.close()
def _send_textmetrics(metrics):
'''
Format metrics for the carbon plaintext protocol
'''
data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']
return '\n'.join(data)
def _walk(path, value, metrics, timestamp, skip):
'''
Recursively include metrics from *value*.
path
The dot-separated path of the metric.
value
A dictionary or value from a dictionary. If a dictionary, ``_walk``
will be called again with the each key/value pair as a new set of
metrics.
metrics
The list of metrics that will be sent to carbon, formatted as::
(path, value, timestamp)
skip
Whether or not to skip metrics when there's an error casting the value
to a float. Defaults to `False`.
'''
log.trace(
'Carbon return walking path: %s, value: %s, metrics: %s, '
'timestamp: %s', path, value, metrics, timestamp
)
if isinstance(value, collections.Mapping):
for key, val in six.iteritems(value):
_walk('{0}.{1}'.format(path, key), val, metrics, timestamp, skip)
elif isinstance(value, list):
for item in value:
_walk('{0}.{1}'.format(path, item), item, metrics, timestamp, skip)
else:
try:
val = float(value)
metrics.append((path, val, timestamp))
except (TypeError, ValueError):
msg = 'Error in carbon returner, when trying to convert metric: ' \
'{0}, with val: {1}'.format(path, value)
if skip:
log.debug(msg)
else:
log.info(msg)
raise
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carbon minion configured with host: %s:%s', host, port)
log.debug('Using carbon protocol: %s', mode)
if not (host and port):
log.error('Host or port not defined')
return
# TODO: possible to use time return from salt job to be slightly more precise?
# convert the jid to unix timestamp?
# {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}
timestamp = int(time.time())
handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics
metrics = []
log.trace('Carbon returning walking data: %s', saltdata)
_walk(metric_base, saltdata, metrics, timestamp, skip)
data = handler(metrics)
log.trace('Carbon inserting data: %s', data)
with _carbon(host, port) as sock:
total_sent_bytes = 0
while total_sent_bytes < len(data):
sent_bytes = sock.send(data[total_sent_bytes:])
if sent_bytes == 0:
log.error('Bytes sent 0, Connection reset?')
return
log.debug('Sent %s bytes to carbon', sent_bytes)
total_sent_bytes += sent_bytes
def event_return(events):
'''
Return event data to remote carbon server
Provide a list of events to be stored in carbon
'''
opts = _get_options({}) # Pass in empty ret, since this is a list of events
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: %s', event)
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
def returner(ret):
'''
Return data to a remote carbon server using the text metric protocol
Each metric will look like::
[module].[function].[minion_id].[metric path [...]].[metric name]
'''
opts = _get_options(ret)
metric_base = ret['fun']
# Strip the hostname from the carbon base if we are returning from virt
# module since then we will get stable metric bases even if the VM is
# migrate from host to host
if not metric_base.startswith('virt.'):
metric_base += '.' + ret['id'].replace('.', '_')
saltdata = ret['return']
_send(saltdata, metric_base, opts)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/carbon_return.py
|
_send_textmetrics
|
python
|
def _send_textmetrics(metrics):
'''
Format metrics for the carbon plaintext protocol
'''
data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']
return '\n'.join(data)
|
Format metrics for the carbon plaintext protocol
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/carbon_return.py#L174-L181
| null |
# -*- coding: utf-8 -*-
'''
Take data from salt and "return" it into a carbon receiver
Add the following configuration to the minion configuration file:
.. code-block:: yaml
carbon.host: <server ip address>
carbon.port: 2003
Errors when trying to convert data to numbers may be ignored by setting
``carbon.skip_on_error`` to `True`:
.. code-block:: yaml
carbon.skip_on_error: True
By default, data will be sent to carbon using the plaintext protocol. To use
the pickle protocol, set ``carbon.mode`` to ``pickle``:
.. code-block:: yaml
carbon.mode: pickle
You can also specify the pattern used for the metric base path (except for virt modules metrics):
carbon.metric_base_pattern: carbon.[minion_id].[module].[function]
These tokens can used :
[module]: salt module
[function]: salt function
[minion_id]: minion id
Default is :
carbon.metric_base_pattern: [module].[function].[minion_id]
Carbon settings may also be configured as:
.. code-block:: yaml
carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
metric_base_pattern: <pattern> | [module].[function].[minion_id]
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
To use the carbon returner, append '--return carbon' to the salt command.
.. code-block:: bash
salt '*' test.ping --return carbon
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_kwargs '{"skip_on_error": False}'
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import logging
import socket
import struct
import time
from contextlib import contextmanager
# Import salt libs
import salt.utils.jid
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import cPickle, map # pylint: disable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'carbon'
def __virtual__():
return __virtualname__
def _get_options(ret):
'''
Returns options used for the carbon returner.
'''
attrs = {'host': 'host',
'port': 'port',
'skip': 'skip_on_error',
'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@contextmanager
def _carbon(host, port):
'''
Context manager to ensure the clean creation and destruction of a socket.
host
The IP or hostname of the carbon server
port
The port that carbon is listening on
'''
carbon_sock = None
try:
carbon_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
carbon_sock.connect((host, port))
except socket.error as err:
log.error('Error connecting to %s:%s, %s', host, port, err)
raise
else:
log.debug('Connected to carbon')
yield carbon_sock
finally:
if carbon_sock is not None:
# Shut down and close socket
log.debug('Destroying carbon socket')
carbon_sock.shutdown(socket.SHUT_RDWR)
carbon_sock.close()
def _send_picklemetrics(metrics):
'''
Format metrics for the carbon pickle protocol
'''
metrics = [(metric_name, (timestamp, value))
for (metric_name, value, timestamp) in metrics]
data = cPickle.dumps(metrics, -1)
payload = struct.pack(b'!L', len(data)) + data
return payload
def _walk(path, value, metrics, timestamp, skip):
'''
Recursively include metrics from *value*.
path
The dot-separated path of the metric.
value
A dictionary or value from a dictionary. If a dictionary, ``_walk``
will be called again with the each key/value pair as a new set of
metrics.
metrics
The list of metrics that will be sent to carbon, formatted as::
(path, value, timestamp)
skip
Whether or not to skip metrics when there's an error casting the value
to a float. Defaults to `False`.
'''
log.trace(
'Carbon return walking path: %s, value: %s, metrics: %s, '
'timestamp: %s', path, value, metrics, timestamp
)
if isinstance(value, collections.Mapping):
for key, val in six.iteritems(value):
_walk('{0}.{1}'.format(path, key), val, metrics, timestamp, skip)
elif isinstance(value, list):
for item in value:
_walk('{0}.{1}'.format(path, item), item, metrics, timestamp, skip)
else:
try:
val = float(value)
metrics.append((path, val, timestamp))
except (TypeError, ValueError):
msg = 'Error in carbon returner, when trying to convert metric: ' \
'{0}, with val: {1}'.format(path, value)
if skip:
log.debug(msg)
else:
log.info(msg)
raise
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carbon minion configured with host: %s:%s', host, port)
log.debug('Using carbon protocol: %s', mode)
if not (host and port):
log.error('Host or port not defined')
return
# TODO: possible to use time return from salt job to be slightly more precise?
# convert the jid to unix timestamp?
# {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}
timestamp = int(time.time())
handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics
metrics = []
log.trace('Carbon returning walking data: %s', saltdata)
_walk(metric_base, saltdata, metrics, timestamp, skip)
data = handler(metrics)
log.trace('Carbon inserting data: %s', data)
with _carbon(host, port) as sock:
total_sent_bytes = 0
while total_sent_bytes < len(data):
sent_bytes = sock.send(data[total_sent_bytes:])
if sent_bytes == 0:
log.error('Bytes sent 0, Connection reset?')
return
log.debug('Sent %s bytes to carbon', sent_bytes)
total_sent_bytes += sent_bytes
def event_return(events):
'''
Return event data to remote carbon server
Provide a list of events to be stored in carbon
'''
opts = _get_options({}) # Pass in empty ret, since this is a list of events
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: %s', event)
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
def returner(ret):
'''
Return data to a remote carbon server using the text metric protocol
Each metric will look like::
[module].[function].[minion_id].[metric path [...]].[metric name]
'''
opts = _get_options(ret)
metric_base = ret['fun']
# Strip the hostname from the carbon base if we are returning from virt
# module since then we will get stable metric bases even if the VM is
# migrate from host to host
if not metric_base.startswith('virt.'):
metric_base += '.' + ret['id'].replace('.', '_')
saltdata = ret['return']
_send(saltdata, metric_base, opts)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/carbon_return.py
|
_walk
|
python
|
def _walk(path, value, metrics, timestamp, skip):
'''
Recursively include metrics from *value*.
path
The dot-separated path of the metric.
value
A dictionary or value from a dictionary. If a dictionary, ``_walk``
will be called again with the each key/value pair as a new set of
metrics.
metrics
The list of metrics that will be sent to carbon, formatted as::
(path, value, timestamp)
skip
Whether or not to skip metrics when there's an error casting the value
to a float. Defaults to `False`.
'''
log.trace(
'Carbon return walking path: %s, value: %s, metrics: %s, '
'timestamp: %s', path, value, metrics, timestamp
)
if isinstance(value, collections.Mapping):
for key, val in six.iteritems(value):
_walk('{0}.{1}'.format(path, key), val, metrics, timestamp, skip)
elif isinstance(value, list):
for item in value:
_walk('{0}.{1}'.format(path, item), item, metrics, timestamp, skip)
else:
try:
val = float(value)
metrics.append((path, val, timestamp))
except (TypeError, ValueError):
msg = 'Error in carbon returner, when trying to convert metric: ' \
'{0}, with val: {1}'.format(path, value)
if skip:
log.debug(msg)
else:
log.info(msg)
raise
|
Recursively include metrics from *value*.
path
The dot-separated path of the metric.
value
A dictionary or value from a dictionary. If a dictionary, ``_walk``
will be called again with the each key/value pair as a new set of
metrics.
metrics
The list of metrics that will be sent to carbon, formatted as::
(path, value, timestamp)
skip
Whether or not to skip metrics when there's an error casting the value
to a float. Defaults to `False`.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/carbon_return.py#L184-L224
| null |
# -*- coding: utf-8 -*-
'''
Take data from salt and "return" it into a carbon receiver
Add the following configuration to the minion configuration file:
.. code-block:: yaml
carbon.host: <server ip address>
carbon.port: 2003
Errors when trying to convert data to numbers may be ignored by setting
``carbon.skip_on_error`` to `True`:
.. code-block:: yaml
carbon.skip_on_error: True
By default, data will be sent to carbon using the plaintext protocol. To use
the pickle protocol, set ``carbon.mode`` to ``pickle``:
.. code-block:: yaml
carbon.mode: pickle
You can also specify the pattern used for the metric base path (except for virt modules metrics):
carbon.metric_base_pattern: carbon.[minion_id].[module].[function]
These tokens can used :
[module]: salt module
[function]: salt function
[minion_id]: minion id
Default is :
carbon.metric_base_pattern: [module].[function].[minion_id]
Carbon settings may also be configured as:
.. code-block:: yaml
carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
metric_base_pattern: <pattern> | [module].[function].[minion_id]
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
To use the carbon returner, append '--return carbon' to the salt command.
.. code-block:: bash
salt '*' test.ping --return carbon
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_kwargs '{"skip_on_error": False}'
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import logging
import socket
import struct
import time
from contextlib import contextmanager
# Import salt libs
import salt.utils.jid
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import cPickle, map # pylint: disable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'carbon'
def __virtual__():
return __virtualname__
def _get_options(ret):
'''
Returns options used for the carbon returner.
'''
attrs = {'host': 'host',
'port': 'port',
'skip': 'skip_on_error',
'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@contextmanager
def _carbon(host, port):
'''
Context manager to ensure the clean creation and destruction of a socket.
host
The IP or hostname of the carbon server
port
The port that carbon is listening on
'''
carbon_sock = None
try:
carbon_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
carbon_sock.connect((host, port))
except socket.error as err:
log.error('Error connecting to %s:%s, %s', host, port, err)
raise
else:
log.debug('Connected to carbon')
yield carbon_sock
finally:
if carbon_sock is not None:
# Shut down and close socket
log.debug('Destroying carbon socket')
carbon_sock.shutdown(socket.SHUT_RDWR)
carbon_sock.close()
def _send_picklemetrics(metrics):
'''
Format metrics for the carbon pickle protocol
'''
metrics = [(metric_name, (timestamp, value))
for (metric_name, value, timestamp) in metrics]
data = cPickle.dumps(metrics, -1)
payload = struct.pack(b'!L', len(data)) + data
return payload
def _send_textmetrics(metrics):
'''
Format metrics for the carbon plaintext protocol
'''
data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']
return '\n'.join(data)
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carbon minion configured with host: %s:%s', host, port)
log.debug('Using carbon protocol: %s', mode)
if not (host and port):
log.error('Host or port not defined')
return
# TODO: possible to use time return from salt job to be slightly more precise?
# convert the jid to unix timestamp?
# {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}
timestamp = int(time.time())
handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics
metrics = []
log.trace('Carbon returning walking data: %s', saltdata)
_walk(metric_base, saltdata, metrics, timestamp, skip)
data = handler(metrics)
log.trace('Carbon inserting data: %s', data)
with _carbon(host, port) as sock:
total_sent_bytes = 0
while total_sent_bytes < len(data):
sent_bytes = sock.send(data[total_sent_bytes:])
if sent_bytes == 0:
log.error('Bytes sent 0, Connection reset?')
return
log.debug('Sent %s bytes to carbon', sent_bytes)
total_sent_bytes += sent_bytes
def event_return(events):
'''
Return event data to remote carbon server
Provide a list of events to be stored in carbon
'''
opts = _get_options({}) # Pass in empty ret, since this is a list of events
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: %s', event)
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
def returner(ret):
'''
Return data to a remote carbon server using the text metric protocol
Each metric will look like::
[module].[function].[minion_id].[metric path [...]].[metric name]
'''
opts = _get_options(ret)
metric_base = ret['fun']
# Strip the hostname from the carbon base if we are returning from virt
# module since then we will get stable metric bases even if the VM is
# migrate from host to host
if not metric_base.startswith('virt.'):
metric_base += '.' + ret['id'].replace('.', '_')
saltdata = ret['return']
_send(saltdata, metric_base, opts)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/carbon_return.py
|
_send
|
python
|
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carbon minion configured with host: %s:%s', host, port)
log.debug('Using carbon protocol: %s', mode)
if not (host and port):
log.error('Host or port not defined')
return
# TODO: possible to use time return from salt job to be slightly more precise?
# convert the jid to unix timestamp?
# {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}
timestamp = int(time.time())
handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics
metrics = []
log.trace('Carbon returning walking data: %s', saltdata)
_walk(metric_base, saltdata, metrics, timestamp, skip)
data = handler(metrics)
log.trace('Carbon inserting data: %s', data)
with _carbon(host, port) as sock:
total_sent_bytes = 0
while total_sent_bytes < len(data):
sent_bytes = sock.send(data[total_sent_bytes:])
if sent_bytes == 0:
log.error('Bytes sent 0, Connection reset?')
return
log.debug('Sent %s bytes to carbon', sent_bytes)
total_sent_bytes += sent_bytes
|
Send the data to carbon
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/carbon_return.py#L227-L266
|
[
"def _send_picklemetrics(metrics):\n '''\n Format metrics for the carbon pickle protocol\n '''\n\n metrics = [(metric_name, (timestamp, value))\n for (metric_name, value, timestamp) in metrics]\n\n data = cPickle.dumps(metrics, -1)\n payload = struct.pack(b'!L', len(data)) + data\n\n return payload\n",
"def _send_textmetrics(metrics):\n '''\n Format metrics for the carbon plaintext protocol\n '''\n\n data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']\n\n return '\\n'.join(data)\n",
"def _walk(path, value, metrics, timestamp, skip):\n '''\n Recursively include metrics from *value*.\n\n path\n The dot-separated path of the metric.\n value\n A dictionary or value from a dictionary. If a dictionary, ``_walk``\n will be called again with the each key/value pair as a new set of\n metrics.\n metrics\n The list of metrics that will be sent to carbon, formatted as::\n\n (path, value, timestamp)\n skip\n Whether or not to skip metrics when there's an error casting the value\n to a float. Defaults to `False`.\n '''\n log.trace(\n 'Carbon return walking path: %s, value: %s, metrics: %s, '\n 'timestamp: %s', path, value, metrics, timestamp\n )\n if isinstance(value, collections.Mapping):\n for key, val in six.iteritems(value):\n _walk('{0}.{1}'.format(path, key), val, metrics, timestamp, skip)\n elif isinstance(value, list):\n for item in value:\n _walk('{0}.{1}'.format(path, item), item, metrics, timestamp, skip)\n\n else:\n try:\n val = float(value)\n metrics.append((path, val, timestamp))\n except (TypeError, ValueError):\n msg = 'Error in carbon returner, when trying to convert metric: ' \\\n '{0}, with val: {1}'.format(path, value)\n if skip:\n log.debug(msg)\n else:\n log.info(msg)\n raise\n"
] |
# -*- coding: utf-8 -*-
'''
Take data from salt and "return" it into a carbon receiver
Add the following configuration to the minion configuration file:
.. code-block:: yaml
carbon.host: <server ip address>
carbon.port: 2003
Errors when trying to convert data to numbers may be ignored by setting
``carbon.skip_on_error`` to `True`:
.. code-block:: yaml
carbon.skip_on_error: True
By default, data will be sent to carbon using the plaintext protocol. To use
the pickle protocol, set ``carbon.mode`` to ``pickle``:
.. code-block:: yaml
carbon.mode: pickle
You can also specify the pattern used for the metric base path (except for virt modules metrics):
carbon.metric_base_pattern: carbon.[minion_id].[module].[function]
These tokens can used :
[module]: salt module
[function]: salt function
[minion_id]: minion id
Default is :
carbon.metric_base_pattern: [module].[function].[minion_id]
Carbon settings may also be configured as:
.. code-block:: yaml
carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
metric_base_pattern: <pattern> | [module].[function].[minion_id]
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
To use the carbon returner, append '--return carbon' to the salt command.
.. code-block:: bash
salt '*' test.ping --return carbon
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_kwargs '{"skip_on_error": False}'
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import logging
import socket
import struct
import time
from contextlib import contextmanager
# Import salt libs
import salt.utils.jid
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import cPickle, map # pylint: disable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'carbon'
def __virtual__():
return __virtualname__
def _get_options(ret):
'''
Returns options used for the carbon returner.
'''
attrs = {'host': 'host',
'port': 'port',
'skip': 'skip_on_error',
'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@contextmanager
def _carbon(host, port):
'''
Context manager to ensure the clean creation and destruction of a socket.
host
The IP or hostname of the carbon server
port
The port that carbon is listening on
'''
carbon_sock = None
try:
carbon_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
carbon_sock.connect((host, port))
except socket.error as err:
log.error('Error connecting to %s:%s, %s', host, port, err)
raise
else:
log.debug('Connected to carbon')
yield carbon_sock
finally:
if carbon_sock is not None:
# Shut down and close socket
log.debug('Destroying carbon socket')
carbon_sock.shutdown(socket.SHUT_RDWR)
carbon_sock.close()
def _send_picklemetrics(metrics):
'''
Format metrics for the carbon pickle protocol
'''
metrics = [(metric_name, (timestamp, value))
for (metric_name, value, timestamp) in metrics]
data = cPickle.dumps(metrics, -1)
payload = struct.pack(b'!L', len(data)) + data
return payload
def _send_textmetrics(metrics):
'''
Format metrics for the carbon plaintext protocol
'''
data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']
return '\n'.join(data)
def _walk(path, value, metrics, timestamp, skip):
'''
Recursively include metrics from *value*.
path
The dot-separated path of the metric.
value
A dictionary or value from a dictionary. If a dictionary, ``_walk``
will be called again with the each key/value pair as a new set of
metrics.
metrics
The list of metrics that will be sent to carbon, formatted as::
(path, value, timestamp)
skip
Whether or not to skip metrics when there's an error casting the value
to a float. Defaults to `False`.
'''
log.trace(
'Carbon return walking path: %s, value: %s, metrics: %s, '
'timestamp: %s', path, value, metrics, timestamp
)
if isinstance(value, collections.Mapping):
for key, val in six.iteritems(value):
_walk('{0}.{1}'.format(path, key), val, metrics, timestamp, skip)
elif isinstance(value, list):
for item in value:
_walk('{0}.{1}'.format(path, item), item, metrics, timestamp, skip)
else:
try:
val = float(value)
metrics.append((path, val, timestamp))
except (TypeError, ValueError):
msg = 'Error in carbon returner, when trying to convert metric: ' \
'{0}, with val: {1}'.format(path, value)
if skip:
log.debug(msg)
else:
log.info(msg)
raise
def event_return(events):
'''
Return event data to remote carbon server
Provide a list of events to be stored in carbon
'''
opts = _get_options({}) # Pass in empty ret, since this is a list of events
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: %s', event)
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
def returner(ret):
'''
Return data to a remote carbon server using the text metric protocol
Each metric will look like::
[module].[function].[minion_id].[metric path [...]].[metric name]
'''
opts = _get_options(ret)
metric_base = ret['fun']
# Strip the hostname from the carbon base if we are returning from virt
# module since then we will get stable metric bases even if the VM is
# migrate from host to host
if not metric_base.startswith('virt.'):
metric_base += '.' + ret['id'].replace('.', '_')
saltdata = ret['return']
_send(saltdata, metric_base, opts)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/carbon_return.py
|
event_return
|
python
|
def event_return(events):
'''
Return event data to remote carbon server
Provide a list of events to be stored in carbon
'''
opts = _get_options({}) # Pass in empty ret, since this is a list of events
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: %s', event)
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
|
Return event data to remote carbon server
Provide a list of events to be stored in carbon
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/carbon_return.py#L269-L281
|
[
"def _send(saltdata, metric_base, opts):\n '''\n Send the data to carbon\n '''\n\n host = opts.get('host')\n port = opts.get('port')\n skip = opts.get('skip')\n metric_base_pattern = opts.get('carbon.metric_base_pattern')\n mode = opts.get('mode').lower() if 'mode' in opts else 'text'\n\n log.debug('Carbon minion configured with host: %s:%s', host, port)\n log.debug('Using carbon protocol: %s', mode)\n\n if not (host and port):\n log.error('Host or port not defined')\n return\n\n # TODO: possible to use time return from salt job to be slightly more precise?\n # convert the jid to unix timestamp?\n # {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}\n timestamp = int(time.time())\n\n handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics\n metrics = []\n log.trace('Carbon returning walking data: %s', saltdata)\n _walk(metric_base, saltdata, metrics, timestamp, skip)\n data = handler(metrics)\n log.trace('Carbon inserting data: %s', data)\n\n with _carbon(host, port) as sock:\n total_sent_bytes = 0\n while total_sent_bytes < len(data):\n sent_bytes = sock.send(data[total_sent_bytes:])\n if sent_bytes == 0:\n log.error('Bytes sent 0, Connection reset?')\n return\n\n log.debug('Sent %s bytes to carbon', sent_bytes)\n total_sent_bytes += sent_bytes\n",
"def _get_options(ret):\n '''\n Returns options used for the carbon returner.\n '''\n attrs = {'host': 'host',\n 'port': 'port',\n 'skip': 'skip_on_error',\n 'mode': 'mode'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''
Take data from salt and "return" it into a carbon receiver
Add the following configuration to the minion configuration file:
.. code-block:: yaml
carbon.host: <server ip address>
carbon.port: 2003
Errors when trying to convert data to numbers may be ignored by setting
``carbon.skip_on_error`` to `True`:
.. code-block:: yaml
carbon.skip_on_error: True
By default, data will be sent to carbon using the plaintext protocol. To use
the pickle protocol, set ``carbon.mode`` to ``pickle``:
.. code-block:: yaml
carbon.mode: pickle
You can also specify the pattern used for the metric base path (except for virt modules metrics):
carbon.metric_base_pattern: carbon.[minion_id].[module].[function]
These tokens can used :
[module]: salt module
[function]: salt function
[minion_id]: minion id
Default is :
carbon.metric_base_pattern: [module].[function].[minion_id]
Carbon settings may also be configured as:
.. code-block:: yaml
carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
metric_base_pattern: <pattern> | [module].[function].[minion_id]
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
To use the carbon returner, append '--return carbon' to the salt command.
.. code-block:: bash
salt '*' test.ping --return carbon
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_kwargs '{"skip_on_error": False}'
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import logging
import socket
import struct
import time
from contextlib import contextmanager
# Import salt libs
import salt.utils.jid
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import cPickle, map # pylint: disable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'carbon'
def __virtual__():
return __virtualname__
def _get_options(ret):
'''
Returns options used for the carbon returner.
'''
attrs = {'host': 'host',
'port': 'port',
'skip': 'skip_on_error',
'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@contextmanager
def _carbon(host, port):
'''
Context manager to ensure the clean creation and destruction of a socket.
host
The IP or hostname of the carbon server
port
The port that carbon is listening on
'''
carbon_sock = None
try:
carbon_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
carbon_sock.connect((host, port))
except socket.error as err:
log.error('Error connecting to %s:%s, %s', host, port, err)
raise
else:
log.debug('Connected to carbon')
yield carbon_sock
finally:
if carbon_sock is not None:
# Shut down and close socket
log.debug('Destroying carbon socket')
carbon_sock.shutdown(socket.SHUT_RDWR)
carbon_sock.close()
def _send_picklemetrics(metrics):
'''
Format metrics for the carbon pickle protocol
'''
metrics = [(metric_name, (timestamp, value))
for (metric_name, value, timestamp) in metrics]
data = cPickle.dumps(metrics, -1)
payload = struct.pack(b'!L', len(data)) + data
return payload
def _send_textmetrics(metrics):
'''
Format metrics for the carbon plaintext protocol
'''
data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']
return '\n'.join(data)
def _walk(path, value, metrics, timestamp, skip):
'''
Recursively include metrics from *value*.
path
The dot-separated path of the metric.
value
A dictionary or value from a dictionary. If a dictionary, ``_walk``
will be called again with the each key/value pair as a new set of
metrics.
metrics
The list of metrics that will be sent to carbon, formatted as::
(path, value, timestamp)
skip
Whether or not to skip metrics when there's an error casting the value
to a float. Defaults to `False`.
'''
log.trace(
'Carbon return walking path: %s, value: %s, metrics: %s, '
'timestamp: %s', path, value, metrics, timestamp
)
if isinstance(value, collections.Mapping):
for key, val in six.iteritems(value):
_walk('{0}.{1}'.format(path, key), val, metrics, timestamp, skip)
elif isinstance(value, list):
for item in value:
_walk('{0}.{1}'.format(path, item), item, metrics, timestamp, skip)
else:
try:
val = float(value)
metrics.append((path, val, timestamp))
except (TypeError, ValueError):
msg = 'Error in carbon returner, when trying to convert metric: ' \
'{0}, with val: {1}'.format(path, value)
if skip:
log.debug(msg)
else:
log.info(msg)
raise
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carbon minion configured with host: %s:%s', host, port)
log.debug('Using carbon protocol: %s', mode)
if not (host and port):
log.error('Host or port not defined')
return
# TODO: possible to use time return from salt job to be slightly more precise?
# convert the jid to unix timestamp?
# {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}
timestamp = int(time.time())
handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics
metrics = []
log.trace('Carbon returning walking data: %s', saltdata)
_walk(metric_base, saltdata, metrics, timestamp, skip)
data = handler(metrics)
log.trace('Carbon inserting data: %s', data)
with _carbon(host, port) as sock:
total_sent_bytes = 0
while total_sent_bytes < len(data):
sent_bytes = sock.send(data[total_sent_bytes:])
if sent_bytes == 0:
log.error('Bytes sent 0, Connection reset?')
return
log.debug('Sent %s bytes to carbon', sent_bytes)
total_sent_bytes += sent_bytes
def returner(ret):
'''
Return data to a remote carbon server using the text metric protocol
Each metric will look like::
[module].[function].[minion_id].[metric path [...]].[metric name]
'''
opts = _get_options(ret)
metric_base = ret['fun']
# Strip the hostname from the carbon base if we are returning from virt
# module since then we will get stable metric bases even if the VM is
# migrate from host to host
if not metric_base.startswith('virt.'):
metric_base += '.' + ret['id'].replace('.', '_')
saltdata = ret['return']
_send(saltdata, metric_base, opts)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/returners/carbon_return.py
|
returner
|
python
|
def returner(ret):
'''
Return data to a remote carbon server using the text metric protocol
Each metric will look like::
[module].[function].[minion_id].[metric path [...]].[metric name]
'''
opts = _get_options(ret)
metric_base = ret['fun']
# Strip the hostname from the carbon base if we are returning from virt
# module since then we will get stable metric bases even if the VM is
# migrate from host to host
if not metric_base.startswith('virt.'):
metric_base += '.' + ret['id'].replace('.', '_')
saltdata = ret['return']
_send(saltdata, metric_base, opts)
|
Return data to a remote carbon server using the text metric protocol
Each metric will look like::
[module].[function].[minion_id].[metric path [...]].[metric name]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/carbon_return.py#L284-L302
|
[
"def _send(saltdata, metric_base, opts):\n '''\n Send the data to carbon\n '''\n\n host = opts.get('host')\n port = opts.get('port')\n skip = opts.get('skip')\n metric_base_pattern = opts.get('carbon.metric_base_pattern')\n mode = opts.get('mode').lower() if 'mode' in opts else 'text'\n\n log.debug('Carbon minion configured with host: %s:%s', host, port)\n log.debug('Using carbon protocol: %s', mode)\n\n if not (host and port):\n log.error('Host or port not defined')\n return\n\n # TODO: possible to use time return from salt job to be slightly more precise?\n # convert the jid to unix timestamp?\n # {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}\n timestamp = int(time.time())\n\n handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics\n metrics = []\n log.trace('Carbon returning walking data: %s', saltdata)\n _walk(metric_base, saltdata, metrics, timestamp, skip)\n data = handler(metrics)\n log.trace('Carbon inserting data: %s', data)\n\n with _carbon(host, port) as sock:\n total_sent_bytes = 0\n while total_sent_bytes < len(data):\n sent_bytes = sock.send(data[total_sent_bytes:])\n if sent_bytes == 0:\n log.error('Bytes sent 0, Connection reset?')\n return\n\n log.debug('Sent %s bytes to carbon', sent_bytes)\n total_sent_bytes += sent_bytes\n",
"def _get_options(ret):\n '''\n Returns options used for the carbon returner.\n '''\n attrs = {'host': 'host',\n 'port': 'port',\n 'skip': 'skip_on_error',\n 'mode': 'mode'}\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n return _options\n"
] |
# -*- coding: utf-8 -*-
'''
Take data from salt and "return" it into a carbon receiver
Add the following configuration to the minion configuration file:
.. code-block:: yaml
carbon.host: <server ip address>
carbon.port: 2003
Errors when trying to convert data to numbers may be ignored by setting
``carbon.skip_on_error`` to `True`:
.. code-block:: yaml
carbon.skip_on_error: True
By default, data will be sent to carbon using the plaintext protocol. To use
the pickle protocol, set ``carbon.mode`` to ``pickle``:
.. code-block:: yaml
carbon.mode: pickle
You can also specify the pattern used for the metric base path (except for virt modules metrics):
carbon.metric_base_pattern: carbon.[minion_id].[module].[function]
These tokens can used :
[module]: salt module
[function]: salt function
[minion_id]: minion id
Default is :
carbon.metric_base_pattern: [module].[function].[minion_id]
Carbon settings may also be configured as:
.. code-block:: yaml
carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
metric_base_pattern: <pattern> | [module].[function].[minion_id]
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
alternative.carbon:
host: <server IP or hostname>
port: <carbon port>
skip_on_error: True
mode: (pickle|text)
To use the carbon returner, append '--return carbon' to the salt command.
.. code-block:: bash
salt '*' test.ping --return carbon
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return carbon --return_kwargs '{"skip_on_error": False}'
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import logging
import socket
import struct
import time
from contextlib import contextmanager
# Import salt libs
import salt.utils.jid
import salt.returners
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import cPickle, map # pylint: disable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'carbon'
def __virtual__():
return __virtualname__
def _get_options(ret):
'''
Returns options used for the carbon returner.
'''
attrs = {'host': 'host',
'port': 'port',
'skip': 'skip_on_error',
'mode': 'mode'}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__)
return _options
@contextmanager
def _carbon(host, port):
'''
Context manager to ensure the clean creation and destruction of a socket.
host
The IP or hostname of the carbon server
port
The port that carbon is listening on
'''
carbon_sock = None
try:
carbon_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
carbon_sock.connect((host, port))
except socket.error as err:
log.error('Error connecting to %s:%s, %s', host, port, err)
raise
else:
log.debug('Connected to carbon')
yield carbon_sock
finally:
if carbon_sock is not None:
# Shut down and close socket
log.debug('Destroying carbon socket')
carbon_sock.shutdown(socket.SHUT_RDWR)
carbon_sock.close()
def _send_picklemetrics(metrics):
'''
Format metrics for the carbon pickle protocol
'''
metrics = [(metric_name, (timestamp, value))
for (metric_name, value, timestamp) in metrics]
data = cPickle.dumps(metrics, -1)
payload = struct.pack(b'!L', len(data)) + data
return payload
def _send_textmetrics(metrics):
'''
Format metrics for the carbon plaintext protocol
'''
data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']
return '\n'.join(data)
def _walk(path, value, metrics, timestamp, skip):
'''
Recursively include metrics from *value*.
path
The dot-separated path of the metric.
value
A dictionary or value from a dictionary. If a dictionary, ``_walk``
will be called again with the each key/value pair as a new set of
metrics.
metrics
The list of metrics that will be sent to carbon, formatted as::
(path, value, timestamp)
skip
Whether or not to skip metrics when there's an error casting the value
to a float. Defaults to `False`.
'''
log.trace(
'Carbon return walking path: %s, value: %s, metrics: %s, '
'timestamp: %s', path, value, metrics, timestamp
)
if isinstance(value, collections.Mapping):
for key, val in six.iteritems(value):
_walk('{0}.{1}'.format(path, key), val, metrics, timestamp, skip)
elif isinstance(value, list):
for item in value:
_walk('{0}.{1}'.format(path, item), item, metrics, timestamp, skip)
else:
try:
val = float(value)
metrics.append((path, val, timestamp))
except (TypeError, ValueError):
msg = 'Error in carbon returner, when trying to convert metric: ' \
'{0}, with val: {1}'.format(path, value)
if skip:
log.debug(msg)
else:
log.info(msg)
raise
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carbon minion configured with host: %s:%s', host, port)
log.debug('Using carbon protocol: %s', mode)
if not (host and port):
log.error('Host or port not defined')
return
# TODO: possible to use time return from salt job to be slightly more precise?
# convert the jid to unix timestamp?
# {'fun': 'test.version', 'jid': '20130113193949451054', 'return': '0.11.0', 'id': 'salt'}
timestamp = int(time.time())
handler = _send_picklemetrics if mode == 'pickle' else _send_textmetrics
metrics = []
log.trace('Carbon returning walking data: %s', saltdata)
_walk(metric_base, saltdata, metrics, timestamp, skip)
data = handler(metrics)
log.trace('Carbon inserting data: %s', data)
with _carbon(host, port) as sock:
total_sent_bytes = 0
while total_sent_bytes < len(data):
sent_bytes = sock.send(data[total_sent_bytes:])
if sent_bytes == 0:
log.error('Bytes sent 0, Connection reset?')
return
log.debug('Sent %s bytes to carbon', sent_bytes)
total_sent_bytes += sent_bytes
def event_return(events):
'''
Return event data to remote carbon server
Provide a list of events to be stored in carbon
'''
opts = _get_options({}) # Pass in empty ret, since this is a list of events
opts['skip'] = True
for event in events:
log.trace('Carbon returner received event: %s', event)
metric_base = event['tag']
saltdata = event['data'].get('data')
_send(saltdata, metric_base, opts)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
saltstack/salt
|
salt/modules/boto_cfn.py
|
exists
|
python
|
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a stack exists.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.exists mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
exists = conn.describe_stacks(name)
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.debug('boto_cfn.exists raised an exception', exc_info=True)
return False
|
Check to see if a stack exists.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.exists mystack region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cfn.py#L71-L90
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Cloud Formation
.. versionadded:: 2015.5.0
:configuration: This module accepts explicit AWS 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
cfn.keyid: GKTADJGHEIQSXMKKRBJ08H
cfn.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cfn.region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto.cloudformation
#pylint: enable=unused-import
from boto.exception import BotoServerError
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs(check_boto3=False)
def __init__(opts):
if HAS_BOTO:
__utils__['boto.assign_funcs'](__name__, 'cfn', module='cloudformation', pack=__salt__)
def describe(name, region=None, key=None, keyid=None, profile=None):
'''
Describe a stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.describe mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
r = conn.describe_stacks(name)
if r:
stack = r[0]
log.debug('Found VPC: %s', stack.stack_id)
keys = ('stack_id', 'description', 'stack_status', 'stack_status_reason', 'tags')
ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)])
o = getattr(stack, 'outputs')
p = getattr(stack, 'parameters')
outputs = {}
parameters = {}
for i in o:
outputs[i.key] = i.value
ret['outputs'] = outputs
for j in p:
parameters[j.key] = j.value
ret['parameters'] = parameters
return {'stack': ret}
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.warning('Could not describe stack %s.\n%s', name, e)
return False
def create(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Create a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.create mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.create_stack(name, template_body, template_url, parameters, notification_arns, disable_rollback,
timeout_in_minutes, capabilities, tags, on_failure, stack_policy_body, stack_policy_url)
except BotoServerError as e:
msg = 'Failed to create stack {0}.\n{1}'.format(name, e)
log.error(msg)
log.debug(e)
return False
def update_stack(name, template_body=None, template_url=None, parameters=None, notification_arns=None,
disable_rollback=False, timeout_in_minutes=None, capabilities=None, tags=None,
use_previous_template=None, stack_policy_during_update_body=None, stack_policy_during_update_url=None,
stack_policy_body=None, stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Update a CFN stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.update_stack mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
update = conn.update_stack(name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, use_previous_template,
stack_policy_during_update_body, stack_policy_during_update_url,
stack_policy_body, stack_policy_url)
log.debug('Updated result is : %s.', update)
return update
except BotoServerError as e:
msg = 'Failed to update stack {0}.'.format(name)
log.debug(e)
log.error(msg)
return six.text_type(e)
def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.delete mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_stack(name)
except BotoServerError as e:
msg = 'Failed to create stack {0}.'.format(name)
log.error(msg)
log.debug(e)
return six.text_type(e)
def get_template(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if attributes are set on a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.get_template mystack
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
template = conn.get_template(name)
log.info('Retrieved template for stack %s', name)
return template
except BotoServerError as e:
log.debug(e)
msg = 'Template {0} does not exist'.format(name)
log.error(msg)
return six.text_type(e)
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None):
'''
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if json is validated and an exception if its not
return conn.validate_template(template_body, template_url)
except BotoServerError as e:
log.debug(e)
msg = 'Error while trying to validate template {0}.'.format(template_body)
log.error(msg)
return six.text_type(e)
|
saltstack/salt
|
salt/modules/boto_cfn.py
|
describe
|
python
|
def describe(name, region=None, key=None, keyid=None, profile=None):
'''
Describe a stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.describe mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
r = conn.describe_stacks(name)
if r:
stack = r[0]
log.debug('Found VPC: %s', stack.stack_id)
keys = ('stack_id', 'description', 'stack_status', 'stack_status_reason', 'tags')
ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)])
o = getattr(stack, 'outputs')
p = getattr(stack, 'parameters')
outputs = {}
parameters = {}
for i in o:
outputs[i.key] = i.value
ret['outputs'] = outputs
for j in p:
parameters[j.key] = j.value
ret['parameters'] = parameters
return {'stack': ret}
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.warning('Could not describe stack %s.\n%s', name, e)
return False
|
Describe a stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.describe mystack region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cfn.py#L93-L133
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Cloud Formation
.. versionadded:: 2015.5.0
:configuration: This module accepts explicit AWS 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
cfn.keyid: GKTADJGHEIQSXMKKRBJ08H
cfn.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cfn.region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto.cloudformation
#pylint: enable=unused-import
from boto.exception import BotoServerError
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs(check_boto3=False)
def __init__(opts):
if HAS_BOTO:
__utils__['boto.assign_funcs'](__name__, 'cfn', module='cloudformation', pack=__salt__)
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a stack exists.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.exists mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
exists = conn.describe_stacks(name)
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.debug('boto_cfn.exists raised an exception', exc_info=True)
return False
def create(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Create a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.create mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.create_stack(name, template_body, template_url, parameters, notification_arns, disable_rollback,
timeout_in_minutes, capabilities, tags, on_failure, stack_policy_body, stack_policy_url)
except BotoServerError as e:
msg = 'Failed to create stack {0}.\n{1}'.format(name, e)
log.error(msg)
log.debug(e)
return False
def update_stack(name, template_body=None, template_url=None, parameters=None, notification_arns=None,
disable_rollback=False, timeout_in_minutes=None, capabilities=None, tags=None,
use_previous_template=None, stack_policy_during_update_body=None, stack_policy_during_update_url=None,
stack_policy_body=None, stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Update a CFN stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.update_stack mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
update = conn.update_stack(name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, use_previous_template,
stack_policy_during_update_body, stack_policy_during_update_url,
stack_policy_body, stack_policy_url)
log.debug('Updated result is : %s.', update)
return update
except BotoServerError as e:
msg = 'Failed to update stack {0}.'.format(name)
log.debug(e)
log.error(msg)
return six.text_type(e)
def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.delete mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_stack(name)
except BotoServerError as e:
msg = 'Failed to create stack {0}.'.format(name)
log.error(msg)
log.debug(e)
return six.text_type(e)
def get_template(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if attributes are set on a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.get_template mystack
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
template = conn.get_template(name)
log.info('Retrieved template for stack %s', name)
return template
except BotoServerError as e:
log.debug(e)
msg = 'Template {0} does not exist'.format(name)
log.error(msg)
return six.text_type(e)
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None):
'''
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if json is validated and an exception if its not
return conn.validate_template(template_body, template_url)
except BotoServerError as e:
log.debug(e)
msg = 'Error while trying to validate template {0}.'.format(template_body)
log.error(msg)
return six.text_type(e)
|
saltstack/salt
|
salt/modules/boto_cfn.py
|
create
|
python
|
def create(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Create a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.create mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.create_stack(name, template_body, template_url, parameters, notification_arns, disable_rollback,
timeout_in_minutes, capabilities, tags, on_failure, stack_policy_body, stack_policy_url)
except BotoServerError as e:
msg = 'Failed to create stack {0}.\n{1}'.format(name, e)
log.error(msg)
log.debug(e)
return False
|
Create a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.create mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cfn.py#L136-L158
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Cloud Formation
.. versionadded:: 2015.5.0
:configuration: This module accepts explicit AWS 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
cfn.keyid: GKTADJGHEIQSXMKKRBJ08H
cfn.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cfn.region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto.cloudformation
#pylint: enable=unused-import
from boto.exception import BotoServerError
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs(check_boto3=False)
def __init__(opts):
if HAS_BOTO:
__utils__['boto.assign_funcs'](__name__, 'cfn', module='cloudformation', pack=__salt__)
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a stack exists.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.exists mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
exists = conn.describe_stacks(name)
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.debug('boto_cfn.exists raised an exception', exc_info=True)
return False
def describe(name, region=None, key=None, keyid=None, profile=None):
'''
Describe a stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.describe mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
r = conn.describe_stacks(name)
if r:
stack = r[0]
log.debug('Found VPC: %s', stack.stack_id)
keys = ('stack_id', 'description', 'stack_status', 'stack_status_reason', 'tags')
ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)])
o = getattr(stack, 'outputs')
p = getattr(stack, 'parameters')
outputs = {}
parameters = {}
for i in o:
outputs[i.key] = i.value
ret['outputs'] = outputs
for j in p:
parameters[j.key] = j.value
ret['parameters'] = parameters
return {'stack': ret}
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.warning('Could not describe stack %s.\n%s', name, e)
return False
def update_stack(name, template_body=None, template_url=None, parameters=None, notification_arns=None,
disable_rollback=False, timeout_in_minutes=None, capabilities=None, tags=None,
use_previous_template=None, stack_policy_during_update_body=None, stack_policy_during_update_url=None,
stack_policy_body=None, stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Update a CFN stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.update_stack mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
update = conn.update_stack(name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, use_previous_template,
stack_policy_during_update_body, stack_policy_during_update_url,
stack_policy_body, stack_policy_url)
log.debug('Updated result is : %s.', update)
return update
except BotoServerError as e:
msg = 'Failed to update stack {0}.'.format(name)
log.debug(e)
log.error(msg)
return six.text_type(e)
def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.delete mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_stack(name)
except BotoServerError as e:
msg = 'Failed to create stack {0}.'.format(name)
log.error(msg)
log.debug(e)
return six.text_type(e)
def get_template(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if attributes are set on a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.get_template mystack
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
template = conn.get_template(name)
log.info('Retrieved template for stack %s', name)
return template
except BotoServerError as e:
log.debug(e)
msg = 'Template {0} does not exist'.format(name)
log.error(msg)
return six.text_type(e)
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None):
'''
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if json is validated and an exception if its not
return conn.validate_template(template_body, template_url)
except BotoServerError as e:
log.debug(e)
msg = 'Error while trying to validate template {0}.'.format(template_body)
log.error(msg)
return six.text_type(e)
|
saltstack/salt
|
salt/modules/boto_cfn.py
|
update_stack
|
python
|
def update_stack(name, template_body=None, template_url=None, parameters=None, notification_arns=None,
disable_rollback=False, timeout_in_minutes=None, capabilities=None, tags=None,
use_previous_template=None, stack_policy_during_update_body=None, stack_policy_during_update_url=None,
stack_policy_body=None, stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Update a CFN stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.update_stack mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
update = conn.update_stack(name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, use_previous_template,
stack_policy_during_update_body, stack_policy_during_update_url,
stack_policy_body, stack_policy_url)
log.debug('Updated result is : %s.', update)
return update
except BotoServerError as e:
msg = 'Failed to update stack {0}.'.format(name)
log.debug(e)
log.error(msg)
return six.text_type(e)
|
Update a CFN stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.update_stack mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cfn.py#L161-L190
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Cloud Formation
.. versionadded:: 2015.5.0
:configuration: This module accepts explicit AWS 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
cfn.keyid: GKTADJGHEIQSXMKKRBJ08H
cfn.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cfn.region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto.cloudformation
#pylint: enable=unused-import
from boto.exception import BotoServerError
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs(check_boto3=False)
def __init__(opts):
if HAS_BOTO:
__utils__['boto.assign_funcs'](__name__, 'cfn', module='cloudformation', pack=__salt__)
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a stack exists.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.exists mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
exists = conn.describe_stacks(name)
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.debug('boto_cfn.exists raised an exception', exc_info=True)
return False
def describe(name, region=None, key=None, keyid=None, profile=None):
'''
Describe a stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.describe mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
r = conn.describe_stacks(name)
if r:
stack = r[0]
log.debug('Found VPC: %s', stack.stack_id)
keys = ('stack_id', 'description', 'stack_status', 'stack_status_reason', 'tags')
ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)])
o = getattr(stack, 'outputs')
p = getattr(stack, 'parameters')
outputs = {}
parameters = {}
for i in o:
outputs[i.key] = i.value
ret['outputs'] = outputs
for j in p:
parameters[j.key] = j.value
ret['parameters'] = parameters
return {'stack': ret}
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.warning('Could not describe stack %s.\n%s', name, e)
return False
def create(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Create a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.create mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.create_stack(name, template_body, template_url, parameters, notification_arns, disable_rollback,
timeout_in_minutes, capabilities, tags, on_failure, stack_policy_body, stack_policy_url)
except BotoServerError as e:
msg = 'Failed to create stack {0}.\n{1}'.format(name, e)
log.error(msg)
log.debug(e)
return False
def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.delete mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_stack(name)
except BotoServerError as e:
msg = 'Failed to create stack {0}.'.format(name)
log.error(msg)
log.debug(e)
return six.text_type(e)
def get_template(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if attributes are set on a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.get_template mystack
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
template = conn.get_template(name)
log.info('Retrieved template for stack %s', name)
return template
except BotoServerError as e:
log.debug(e)
msg = 'Template {0} does not exist'.format(name)
log.error(msg)
return six.text_type(e)
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None):
'''
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if json is validated and an exception if its not
return conn.validate_template(template_body, template_url)
except BotoServerError as e:
log.debug(e)
msg = 'Error while trying to validate template {0}.'.format(template_body)
log.error(msg)
return six.text_type(e)
|
saltstack/salt
|
salt/modules/boto_cfn.py
|
delete
|
python
|
def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.delete mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_stack(name)
except BotoServerError as e:
msg = 'Failed to create stack {0}.'.format(name)
log.error(msg)
log.debug(e)
return six.text_type(e)
|
Delete a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.delete mystack region=us-east-1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cfn.py#L193-L211
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Cloud Formation
.. versionadded:: 2015.5.0
:configuration: This module accepts explicit AWS 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
cfn.keyid: GKTADJGHEIQSXMKKRBJ08H
cfn.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cfn.region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto.cloudformation
#pylint: enable=unused-import
from boto.exception import BotoServerError
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs(check_boto3=False)
def __init__(opts):
if HAS_BOTO:
__utils__['boto.assign_funcs'](__name__, 'cfn', module='cloudformation', pack=__salt__)
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a stack exists.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.exists mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
exists = conn.describe_stacks(name)
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.debug('boto_cfn.exists raised an exception', exc_info=True)
return False
def describe(name, region=None, key=None, keyid=None, profile=None):
'''
Describe a stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.describe mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
r = conn.describe_stacks(name)
if r:
stack = r[0]
log.debug('Found VPC: %s', stack.stack_id)
keys = ('stack_id', 'description', 'stack_status', 'stack_status_reason', 'tags')
ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)])
o = getattr(stack, 'outputs')
p = getattr(stack, 'parameters')
outputs = {}
parameters = {}
for i in o:
outputs[i.key] = i.value
ret['outputs'] = outputs
for j in p:
parameters[j.key] = j.value
ret['parameters'] = parameters
return {'stack': ret}
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.warning('Could not describe stack %s.\n%s', name, e)
return False
def create(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Create a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.create mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.create_stack(name, template_body, template_url, parameters, notification_arns, disable_rollback,
timeout_in_minutes, capabilities, tags, on_failure, stack_policy_body, stack_policy_url)
except BotoServerError as e:
msg = 'Failed to create stack {0}.\n{1}'.format(name, e)
log.error(msg)
log.debug(e)
return False
def update_stack(name, template_body=None, template_url=None, parameters=None, notification_arns=None,
disable_rollback=False, timeout_in_minutes=None, capabilities=None, tags=None,
use_previous_template=None, stack_policy_during_update_body=None, stack_policy_during_update_url=None,
stack_policy_body=None, stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Update a CFN stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.update_stack mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
update = conn.update_stack(name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, use_previous_template,
stack_policy_during_update_body, stack_policy_during_update_url,
stack_policy_body, stack_policy_url)
log.debug('Updated result is : %s.', update)
return update
except BotoServerError as e:
msg = 'Failed to update stack {0}.'.format(name)
log.debug(e)
log.error(msg)
return six.text_type(e)
def get_template(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if attributes are set on a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.get_template mystack
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
template = conn.get_template(name)
log.info('Retrieved template for stack %s', name)
return template
except BotoServerError as e:
log.debug(e)
msg = 'Template {0} does not exist'.format(name)
log.error(msg)
return six.text_type(e)
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None):
'''
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if json is validated and an exception if its not
return conn.validate_template(template_body, template_url)
except BotoServerError as e:
log.debug(e)
msg = 'Error while trying to validate template {0}.'.format(template_body)
log.error(msg)
return six.text_type(e)
|
saltstack/salt
|
salt/modules/boto_cfn.py
|
get_template
|
python
|
def get_template(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if attributes are set on a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.get_template mystack
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
template = conn.get_template(name)
log.info('Retrieved template for stack %s', name)
return template
except BotoServerError as e:
log.debug(e)
msg = 'Template {0} does not exist'.format(name)
log.error(msg)
return six.text_type(e)
|
Check to see if attributes are set on a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.get_template mystack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cfn.py#L214-L234
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Cloud Formation
.. versionadded:: 2015.5.0
:configuration: This module accepts explicit AWS 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
cfn.keyid: GKTADJGHEIQSXMKKRBJ08H
cfn.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cfn.region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto.cloudformation
#pylint: enable=unused-import
from boto.exception import BotoServerError
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs(check_boto3=False)
def __init__(opts):
if HAS_BOTO:
__utils__['boto.assign_funcs'](__name__, 'cfn', module='cloudformation', pack=__salt__)
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a stack exists.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.exists mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
exists = conn.describe_stacks(name)
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.debug('boto_cfn.exists raised an exception', exc_info=True)
return False
def describe(name, region=None, key=None, keyid=None, profile=None):
'''
Describe a stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.describe mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
r = conn.describe_stacks(name)
if r:
stack = r[0]
log.debug('Found VPC: %s', stack.stack_id)
keys = ('stack_id', 'description', 'stack_status', 'stack_status_reason', 'tags')
ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)])
o = getattr(stack, 'outputs')
p = getattr(stack, 'parameters')
outputs = {}
parameters = {}
for i in o:
outputs[i.key] = i.value
ret['outputs'] = outputs
for j in p:
parameters[j.key] = j.value
ret['parameters'] = parameters
return {'stack': ret}
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.warning('Could not describe stack %s.\n%s', name, e)
return False
def create(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Create a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.create mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.create_stack(name, template_body, template_url, parameters, notification_arns, disable_rollback,
timeout_in_minutes, capabilities, tags, on_failure, stack_policy_body, stack_policy_url)
except BotoServerError as e:
msg = 'Failed to create stack {0}.\n{1}'.format(name, e)
log.error(msg)
log.debug(e)
return False
def update_stack(name, template_body=None, template_url=None, parameters=None, notification_arns=None,
disable_rollback=False, timeout_in_minutes=None, capabilities=None, tags=None,
use_previous_template=None, stack_policy_during_update_body=None, stack_policy_during_update_url=None,
stack_policy_body=None, stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Update a CFN stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.update_stack mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
update = conn.update_stack(name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, use_previous_template,
stack_policy_during_update_body, stack_policy_during_update_url,
stack_policy_body, stack_policy_url)
log.debug('Updated result is : %s.', update)
return update
except BotoServerError as e:
msg = 'Failed to update stack {0}.'.format(name)
log.debug(e)
log.error(msg)
return six.text_type(e)
def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.delete mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_stack(name)
except BotoServerError as e:
msg = 'Failed to create stack {0}.'.format(name)
log.error(msg)
log.debug(e)
return six.text_type(e)
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None):
'''
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if json is validated and an exception if its not
return conn.validate_template(template_body, template_url)
except BotoServerError as e:
log.debug(e)
msg = 'Error while trying to validate template {0}.'.format(template_body)
log.error(msg)
return six.text_type(e)
|
saltstack/salt
|
salt/modules/boto_cfn.py
|
validate_template
|
python
|
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None):
'''
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if json is validated and an exception if its not
return conn.validate_template(template_body, template_url)
except BotoServerError as e:
log.debug(e)
msg = 'Error while trying to validate template {0}.'.format(template_body)
log.error(msg)
return six.text_type(e)
|
Validate cloudformation template
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.validate_template mystack-template
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cfn.py#L237-L258
| null |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Cloud Formation
.. versionadded:: 2015.5.0
:configuration: This module accepts explicit AWS 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
cfn.keyid: GKTADJGHEIQSXMKKRBJ08H
cfn.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration:
.. code-block:: yaml
cfn.region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
#pylint: disable=E0602
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt libs
from salt.ext import six
import salt.utils.versions
log = logging.getLogger(__name__)
# Import third party libs
# pylint: disable=import-error
try:
#pylint: disable=unused-import
import boto
import boto.cloudformation
#pylint: enable=unused-import
from boto.exception import BotoServerError
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist.
'''
return salt.utils.versions.check_boto_reqs(check_boto3=False)
def __init__(opts):
if HAS_BOTO:
__utils__['boto.assign_funcs'](__name__, 'cfn', module='cloudformation', pack=__salt__)
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a stack exists.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.exists mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
exists = conn.describe_stacks(name)
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.debug('boto_cfn.exists raised an exception', exc_info=True)
return False
def describe(name, region=None, key=None, keyid=None, profile=None):
'''
Describe a stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.describe mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
# Returns an object if stack exists else an exception
r = conn.describe_stacks(name)
if r:
stack = r[0]
log.debug('Found VPC: %s', stack.stack_id)
keys = ('stack_id', 'description', 'stack_status', 'stack_status_reason', 'tags')
ret = dict([(k, getattr(stack, k)) for k in keys if hasattr(stack, k)])
o = getattr(stack, 'outputs')
p = getattr(stack, 'parameters')
outputs = {}
parameters = {}
for i in o:
outputs[i.key] = i.value
ret['outputs'] = outputs
for j in p:
parameters[j.key] = j.value
ret['parameters'] = parameters
return {'stack': ret}
log.debug('Stack %s exists.', name)
return True
except BotoServerError as e:
log.warning('Could not describe stack %s.\n%s', name, e)
return False
def create(name, template_body=None, template_url=None, parameters=None, notification_arns=None, disable_rollback=None,
timeout_in_minutes=None, capabilities=None, tags=None, on_failure=None, stack_policy_body=None,
stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Create a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.create mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.create_stack(name, template_body, template_url, parameters, notification_arns, disable_rollback,
timeout_in_minutes, capabilities, tags, on_failure, stack_policy_body, stack_policy_url)
except BotoServerError as e:
msg = 'Failed to create stack {0}.\n{1}'.format(name, e)
log.error(msg)
log.debug(e)
return False
def update_stack(name, template_body=None, template_url=None, parameters=None, notification_arns=None,
disable_rollback=False, timeout_in_minutes=None, capabilities=None, tags=None,
use_previous_template=None, stack_policy_during_update_body=None, stack_policy_during_update_url=None,
stack_policy_body=None, stack_policy_url=None, region=None, key=None, keyid=None, profile=None):
'''
Update a CFN stack.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.update_stack mystack template_url='https://s3.amazonaws.com/bucket/template.cft' \
region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
update = conn.update_stack(name, template_body, template_url, parameters, notification_arns,
disable_rollback, timeout_in_minutes, capabilities, tags, use_previous_template,
stack_policy_during_update_body, stack_policy_during_update_url,
stack_policy_body, stack_policy_url)
log.debug('Updated result is : %s.', update)
return update
except BotoServerError as e:
msg = 'Failed to update stack {0}.'.format(name)
log.debug(e)
log.error(msg)
return six.text_type(e)
def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.delete mystack region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
return conn.delete_stack(name)
except BotoServerError as e:
msg = 'Failed to create stack {0}.'.format(name)
log.error(msg)
log.debug(e)
return six.text_type(e)
def get_template(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if attributes are set on a CFN stack.
CLI Example:
.. code-block:: bash
salt myminion boto_cfn.get_template mystack
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
template = conn.get_template(name)
log.info('Retrieved template for stack %s', name)
return template
except BotoServerError as e:
log.debug(e)
msg = 'Template {0} does not exist'.format(name)
log.error(msg)
return six.text_type(e)
|
saltstack/salt
|
salt/modules/service.py
|
run
|
python
|
def run(name, action):
'''
Run the specified service with an action.
.. versionadded:: 2015.8.1
name
Service name.
action
Action name (like start, stop, reload, restart).
CLI Example:
.. code-block:: bash
salt '*' service.run apache2 reload
salt '*' service.run postgresql initdb
'''
cmd = os.path.join(
_GRAINMAP.get(__grains__.get('os'), '/etc/init.d'),
name
) + ' ' + action
return not __salt__['cmd.retcode'](cmd, python_shell=False)
|
Run the specified service with an action.
.. versionadded:: 2015.8.1
name
Service name.
action
Action name (like start, stop, reload, restart).
CLI Example:
.. code-block:: bash
salt '*' service.run apache2 reload
salt '*' service.run postgresql initdb
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/service.py#L60-L83
| null |
# -*- coding: utf-8 -*-
'''
If Salt's OS detection does not identify a different virtual service module, the minion will fall back to using this basic module, which simply wraps sysvinit scripts.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import fnmatch
import re
__func_alias__ = {
'reload_': 'reload'
}
_GRAINMAP = {
'Arch': '/etc/rc.d',
'Arch ARM': '/etc/rc.d'
}
def __virtual__():
'''
Only work on systems which exclusively use sysvinit
'''
# Disable on these platforms, specific service modules exist:
disable = set((
'RedHat',
'CentOS',
'Amazon',
'ScientificLinux',
'CloudLinux',
'Fedora',
'Gentoo',
'Ubuntu',
'Debian',
'Devuan',
'ALT',
'OEL',
'Linaro',
'elementary OS',
'McAfee OS Server',
'Raspbian',
'SUSE',
))
if __grains__.get('os') in disable:
return (False, 'Your OS is on the disabled list')
# Disable on all non-Linux OSes as well
if __grains__['kernel'] != 'Linux':
return (False, 'Non Linux OSes are not supported')
init_grain = __grains__.get('init')
if init_grain not in (None, 'sysvinit', 'unknown'):
return (False, 'Minion is running {0}'.format(init_grain))
elif __utils__['systemd.booted'](__context__):
# Should have been caught by init grain check, but check just in case
return (False, 'Minion is running systemd')
return 'service'
def start(name):
'''
Start the specified service
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
'''
return run(name, 'start')
def stop(name):
'''
Stop the specified service
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
'''
return run(name, 'stop')
def restart(name):
'''
Restart the specified service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
return run(name, 'restart')
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to PID or empty
string is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Signature to use to find the service via ps
Returns:
string: PID if running, empty otherwise
dict: Maps service name to PID if running, empty string otherwise
CLI Example:
.. code-block:: bash
salt '*' service.status <service name> [service signature]
'''
if sig:
return __salt__['status.pid'](sig)
contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name))
if contains_globbing:
services = fnmatch.filter(get_all(), name)
else:
services = [name]
results = {}
for service in services:
results[service] = __salt__['status.pid'](service)
if contains_globbing:
return results
return results[name]
def reload_(name):
'''
Refreshes config files by calling service reload. Does not perform a full
restart.
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
return run(name, 'reload')
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
'''
return name in get_all()
def missing(name):
'''
The inverse of service.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing sshd
'''
return name not in get_all()
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
if not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')):
return []
return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.